【问题标题】:Get full path without filename from path that includes filename从包含文件名的路径中获取没有文件名的完整路径
【发布时间】:2011-04-19 02:41:39
【问题描述】:

System.IO.Path 中是否有任何内容只提供文件路径?

例如,如果我有一个string

@"c:\webserver\public\myCompany\configs\promo.xml",

有什么BCL方法可以给我

"c:\webserver\public\myCompany\configs\"?

【问题讨论】:

  • FWIW:我已经“放弃”了 Path 对“路径”的处理,我们使用我们自己的方法,对 UNC 有更好的期望和一致性(尝试在 UNC 路径上使用 GetDirectoryName)和约定(例如尾随 /)。
  • 除非文件或目录存在,否则无法知道promo.xml 是否指定了同名的文件或目录。这可能就是为什么Path.GetDirectoryName() 实现如此简单并且只是截断最后一段,或者删除尾部斜杠(如果有的话)的原因。

标签: c# file path


【解决方案1】:

Path.GetDirectoryName()... 但是你需要知道你传递给它的路径确实包含一个文件名;它只是从路径中删除最后一位,无论是文件名还是目录名(它实际上不知道是哪个)。

您可以先在您的路径上测试File.Exists() 和/或Directory.Exists() 来验证是否需要调用Path.GetDirectoryName

【讨论】:

  • 无需致电File.Exists()。实际上,如果您查找目录名称的原因是在它不存在的情况下创建它,这会适得其反。
  • 他的示例明确指出了带有文件名的路径。如果这是他正在测试的路径的模式,并且如果这些路径代表现有文件,那么检查 File.Exists() 肯定会有用,您不同意吗?因为情况可能不是这样,当然,我只是建议他“可以”在文件和/或目录上使用 Exists 方法;显然,根据他的情况。
  • 是的,带有文件名的路径。没有任何内容表明文件存在,因为文件名是第一位的。
  • 如我所说;这是一个选项,它可能会有所帮助,具体取决于对路径的了解。或者它可能根本没有必要。但是在同一路径上测试 File.Exists() 和 Directory.Exists() 是一种快速简便的方法,可以知道存在的路径是文件还是目录。
  • 作为快速参考,与问题无关,并且“明显”对待,您需要包含 System.IO 才能使其工作。
【解决方案2】:
Console.WriteLine(Path.GetDirectoryName(@"C:\hello\my\dear\world.hm")); 

【讨论】:

    【解决方案3】:

    Path.GetDirectoryName() 返回目录名称,因此您可以调用Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar

    【讨论】:

      【解决方案4】:
          string fileAndPath = @"c:\webserver\public\myCompany\configs\promo.xml";
      
          string currentDirectory = Path.GetDirectoryName(fileAndPath);
      
          string fullPathOnly = Path.GetFullPath(currentDirectory);
      

      当前目录:c:\webserver\public\myCompany\configs

      fullPathOnly: c:\webserver\public\myCompany\configs

      【讨论】:

        【解决方案5】:

        如图所示使用GetParent(),效果很好。 根据需要添加错误检查。

        var fn = openFileDialogSapTable.FileName;
        var currentPath = Path.GetFullPath( fn );
        currentPath = Directory.GetParent(currentPath).FullName;
        

        【讨论】:

          【解决方案6】:

          我用过这个,效果很好:

          string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));
          
          foreach (string file in filePaths)
          {   
              if (comboBox1.SelectedItem.ToString() == "")
              {
                  if (file.Contains("c"))
                  {
                      comboBox2.Items.Add(Path.GetFileName(file));
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2011-01-08
            • 1970-01-01
            • 2011-04-13
            • 2012-01-11
            • 1970-01-01
            • 1970-01-01
            • 2011-07-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多