【问题标题】:Getting the parentDirectory of a file in a unc path c# 2010在 unc 路径 c# 2010 中获取文件的 parentDirectory
【发布时间】:2014-07-04 13:43:52
【问题描述】:

我需要首先确定这是一个 UNCPath 如果是这样获取文件目录 有没有一种方法可以识别路径是否为 UNC 路径? 如何获取文件的 parent.Parent.directory?

\\MyServer\\MySharedDrive\\MyDirectory\\MySubDirectory\\Myfile.csv

 Wanted result and should work however deep

 \\MyServer\\MySharedDrive\\MyDirectory

这样我就可以将另一个文件保存到上述目录中。 我想我做不到

  Path.Combine("\\MyServer\\MySharedDrive\\MyDirectory",myNewFile.csv)

有什么建议吗?

非常感谢

【问题讨论】:

    标签: c#


    【解决方案1】:

    要获取父目录然后创建新路径,您可以这样做:

    string path = "\\MyServer\\MySharedDrive\\MyDirectory\\MySubDirectory\\Myfile.csv";
    DirectoryInfo directory = new DirectoryInfo(Path.GetDirectoryName(path));
    string finalPath = Path.Combine(directory.Parent.FullName, "myNewFile.csv"
    

    要检查路径是否为 UNC,请检查 this post

    【讨论】:

    • 您好,感谢您抽出宝贵的时间!这足以检查它是否是 unc 路径 myPath.Contains(@"\\"))
    • 不,一点也不,至少检查应该是检查路径是否以myPath.StartsWith("\\\\")之类的双反斜杠开头,但是您应该查看此帖子以了解详细信息回答。 stackoverflow.com/questions/520753/…
    【解决方案2】:

    来自 MSDN

    Path 类的大多数成员不与文件系统交互 并且不验证路径字符串指定的文件是否存在

    再次来自 MSDN Path class

    在接受路径的成员中,路径可以引用文件或只是一个 目录。指定路径也可以指相对路径或 服务器和共享名称的通用命名约定 (UNC) 路径

    说了,你可以写

    string myUNCPath = @"\\MyServer\MySharedDrive\MyDirectory\MySubDirectory\Myfile.csv";
    string myParent = Path.GetDirectoryName(Path.GetDirectoryName(myUNCPath));
    string finalFile = Path.Combine(@"\\MyServer\MySharedDrive\MyDirectory","myNewFile.csv");
    

    作为安全检查,您应该对 Path.GetDirectoryName 执行两个单独的调用,因为如果您只有一层深的子目录,那么 Path.GetDirectoryName 的结果将为空

    例如,如果初始 UNC 路径是

    string myUNCPath = @"\\MyServer\MySharedDrive\MyDirectory\Myfile.csv";
    string myParent = Path.GetDirectoryName(myUNCPath);
    if(!string.IsNullOrWhiteSpace(myParent))
    {
         myParent = Path.GetDirectoryName(myParent);
         if(!string.IsNullOrWhiteSpace(myParent))
         {
             string finalFile = Path.Combine(myParent, "myNewFile.csv");
             .....
         }
     }
    

    对于与您的第一个问题相关的部分,UNC 路径的发现相对容易。 请参阅 Windows 开发中心上有关 Paths and Files 的这篇文章

    Console.WriteLine(IsUNCPath(myUNCPath));
    ......
    
    bool IsUNCPath(string pathToCheck)
    {
        return pathToCheck.StartsWith(@"\\");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      相关资源
      最近更新 更多