【问题标题】:Get parent directory of parent directory获取父目录的父目录
【发布时间】:2014-01-13 23:28:32
【问题描述】:

我有一个与网络上某个位置相关的字符串,我需要从该位置获取第二个目录。

字符串可以是以下格式:

string networkDir = "\\\\networkLocation\\staff\\users\\username";

在这种情况下,我需要staff 文件夹并可以使用以下逻辑:

string parentDir1 = Path.GetDirectoryName(networkDir);
string parentDir2 = Path.GetPathRoot(Path.GetDirectoryName(networkDir));

但是,如果字符串的格式为:

string networkDir = "\\\\networkLocation\\users\\username";

我只需要networkLocation 部分,parentDir2 返回 null。

我该怎么做?

澄清一下:如果根目录恰好是给定文件夹上方的目录 2,那么这就是我需要返回的内容

【问题讨论】:

  • 仅供参考:您可以编写带有 @ 前缀的文字字符串,以使它们更具可读性/可复制性/等等... @"\\networkLocation\users\username"。我不太清楚你想从这个问题中做什么。

标签: c#


【解决方案1】:

您可以使用 System.IO.DirectoryInfo 类:

DirectoryInfo networkDir=new DirectoryInfo(@"\\Path\here\now\username");
DirectoryInfo twoLevelsUp=networkDir.Parent.Parent;

【讨论】:

  • 如果字符串格式为\\Path\here\username,则返回null
  • 如果你一直备份到根目录,即C:\或\\server\share,它将返回null。
  • 如果根目录恰好是给定文件夹上方的目录 2,那么这就是我需要返回的内容
【解决方案2】:
DirectoryInfo d = new DirectoryInfo("\\\\networkLocation\\test\\test");
if (d.Parent.Parent != null) 
{ 
    string up2 = d.Parent.Parent.ToString(); 
}
else 
{ 
    string up2 = d.Root.ToString().Split(Path.DirectorySeparatorChar)[2]; 
}

是我一直在寻找的。对于造成的任何混乱,我们深表歉意!

【讨论】:

  • 在处理路径操作时使用 strings 不是一个好主意。考虑改用DirectoryInfo
【解决方案3】:

我遇到了类似的情况。看起来你可以打电话给GetDirectoryName 两次!

var root = Path.GetDirectoryName( Path.GetDirectoryName( path ) );

维奥拉!

【讨论】:

    【解决方案4】:

    你可以试试这个(我一直在命令行/批处理文件中使用它)。

    string twolevelsup = Path.Combine("\\\\networkLocation\\staff\\users\\username", "..\\..\\"); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 2018-07-15
      • 1970-01-01
      • 2012-01-29
      • 2017-04-09
      • 1970-01-01
      • 2016-05-18
      相关资源
      最近更新 更多