【问题标题】:How to get parent directory in a path c#?如何在路径c#中获取父目录?
【发布时间】:2016-06-28 08:49:53
【问题描述】:

这是我的路径示例E:\test\img\sig.jpg 我想得到E:\test\img 来创建目录 我尝试拆分,但它是 img 所以我尝试功能 Directory.CreateDirectory 和路径是E:\test\img\sig.jpg\ 说说我的想法?

【问题讨论】:

  • 请您编辑您的问题,向我们展示您的尝试,然后我们可以提供帮助。
  • 提问前先google一下
  • 也许你应该改变你的标题。在您的示例中,父目录为:E:\test

标签: c#


【解决方案1】:

推荐的方式是使用Path.GetDirectoryName():

string file = @"E:\test\img\sig.jpg";
string path = Path.GetDirectoryName(file); // results in @"E:\test\img"

【讨论】:

    【解决方案2】:

    使用Path.GetDirectoryName 返回指定路径字符串的目录信息。

    string directoryName = Path.GetDirectoryName(filePath);
    

    【讨论】:

      【解决方案3】:

      Path 类包含很多有用的路径处理方法,比手动字符串操作更可靠:

      var directoryComponent = Path.GetDirectoryName(@"E:\test\img\sig.jpg");
      // yields `E:\test\img`
      

      为了完整起见,我想提一下Path.Combine,它的作用正好相反:

      var dirAndFile = Path.Combine(@"E:\test\img", "sig.jpg");
      // no more checking for trailing slashes, hooray!
      

      要创建目录,您可以使用Directory.Create。注意it is not necessary to check if the directory exists first

      【讨论】:

        【解决方案4】:

        您可以尝试使用此代码来查找目录名称。 System.IO.FileInfo fi = new System.IO.FileInfo(@"E:\test\img\sig.jpg"); string dirname = fi.DirectoryName;

        并创建目录 Directory.CreateDirectory(目录名);

        【讨论】:

          【解决方案5】:

          另一种解决方案是:

          FileInfo f = new FileInfo(@"E:\test\img\sig.jpg");
          if (f.Exists)
          {
              string dirName= f.DirectoryName;
          }
          

          【讨论】:

            猜你喜欢
            • 2020-03-05
            • 1970-01-01
            • 2020-12-06
            • 1970-01-01
            • 1970-01-01
            • 2019-02-18
            • 1970-01-01
            • 1970-01-01
            • 2014-03-10
            相关资源
            最近更新 更多