【问题标题】:C# How to get current path and go up one folderC#如何获取当前路径并上一个文件夹
【发布时间】:2019-06-19 11:23:31
【问题描述】:

我能够得到当前路径:

Request.PhysicalApplicationPath;

例如是C:\consoleapp\capp\files

我想上一个文件夹到: C:\consoleapp\capp\

然后到另一个文件夹 C:\consoleapp\capp\images

我该怎么做?

【问题讨论】:

  • 检查Path静态方法。

标签: c# file-io path


【解决方案1】:

你应该使用 System.IO
您可以使用DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory()),然后只需使用di.Parent

【讨论】:

    【解决方案2】:

    以下应该可以帮助您到达父目录,然后基于它创建新路径。

    var path = @"C:\consoleapp\capp\files"; // or in your case Request.PhysicalApplicationPath
    var parent = Directory.GetParent(path).FullName;
    var newPath = Path.Combine(parent,"Images");
    

    您可以阅读有关 Directory.GetParent() here 的更多详细信息。 Path.Combine 允许您将多个字符串组合到路径中。你可以阅读更多关于 Path.Combine here

    输出

    parent = C:\consoleapp\capp
    newPath = C:\consoleapp\capp\Images
    

    【讨论】:

    • 这部分问题已经有duplicate
    • 我也希望强迫你回答另一个部分。
    • @Sinatr 猜猜看,我没看到那部分 :)
    【解决方案3】:

    来自How to navigate a few folders up?

    string path = @"C:\Folder1\Folder2\Folder3\Folder4";
    string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\"));
    

    向上导航后,您可以再次附加新文件夹

    【讨论】:

    • 为什么你删除了concat 2 strings question。一旦清楚就很有趣。我对其进行了编辑以使其更清晰。取消删除,我可以回答
    猜你喜欢
    • 1970-01-01
    • 2017-04-16
    • 2013-07-26
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多