【问题标题】:How do I find the parent directory of a path?如何找到路径的父目录?
【发布时间】:2012-07-06 13:35:31
【问题描述】:

如何获取目录的父级,例如:

string upDir = GetOneLvlUp(@"C:\AAA\BBB\CCC\DDD\");

Output:  C:\AAA\BBB\CCC\

【问题讨论】:

标签: .net


【解决方案1】:
upDir = Directory.GetParent(path).FullName;

【讨论】:

  • 注意:Directory.GetParent(@"C:\AAA\BBB\CCC\DDD\").FullName == @"C:\AAA\BBB\CCC\DDD".
  • 这是不正确的。正如@SergejLoos 上面所说,这只会删除斜线。我们想做这个 DirectoryInfo(yourPath).Parent.FullName 代替。
  • @DezUdezue,这些天我不在 .net 上工作,也不知道变化。但是,如果您编写的是 .net 内置函数,那么这是 .net 中的不一致,您可以将其报告为错误。
【解决方案2】:
【解决方案3】:
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string parentDir = Directory.GetParent(path).FullName;

【讨论】:

    【解决方案4】:
    var upDir = new DirectoryInfo(yourPath).Parent.FullName;
    

    【讨论】:

    • 不对:upDir = Directory.GetParent(path).FullName;因为如果路径字符串以字符“\”结尾,可能会返回错误的父路径。
    猜你喜欢
    • 2016-06-29
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多