从包含文件名的路径获取没有文件名的完整路径

Can*_*ain 185 c# file path

有没有内置的东西System.IO.Path只给我文件路径?

例如,如果我有 string

@ "C:\网络服务器\ PUBLIC\myCompany的\ CONFIGS\promo.xml"

是否有任何BCL方法可以给我

"C:\网络服务器\ PUBLIC\myCompany的\ CONFIGS \"?

And*_*ber 224

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

您可以先通过测试File.Exists()和/或Directory.Exists()在您的路径上验证是否需要打电话Path.GetDirectoryName

  • 就像我说的; 它是一个选项,它可能会有所帮助,具体取决于对路径的了解.或者根本没有必要.但是,在同一路径上测试File.Exists()和Directory.Exists()是一种快速简便的方法,可以了解存在的路径是文件还是目录. (4认同)
  • 作为一个快速参考,在问题冗余和"明显"处理方面,你需要包含`System.IO`来实现这个目的. (4认同)
  • 没有必要调用`File.Exists()`.实际上,如果您找到目录名称的原因是创建它(如果它尚不存在),那么它会相当适得其反. (2认同)
  • 他的示例明确指出了带有文件名的路径.如果这是他正在测试的路径模式,如果这些路径代表现有文件,检查File.Exists()肯定会有用,你不同意吗?当然,情况可能不然,我只是建议他"可以"在文件和/或目录上使用Exists方法; 显然,适合他的情况. (2认同)

exp*_*rer 67

Console.WriteLine(Path.GetDirectoryName(@"C:\hello\my\dear\world.hm")); 
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的。记住`using System.IO;`来使用路径方法 (2认同)

Jon*_*nna 51

Path.GetDirectoryName()返回目录名称,因此您可以调用所需的(使用尾部反向solidus字符)Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar.

  • +1 Path.DirectorySeparatorChar很有帮助 (7认同)

Kob*_*ams 8

    string fileAndPath = @"c:\webserver\public\myCompany\configs\promo.xml";

    string currentDirectory = Path.GetDirectoryName(fileAndPath);

    string fullPathOnly = Path.GetFullPath(currentDirectory);
Run Code Online (Sandbox Code Playgroud)

  • 请提供有关上述代码如何回答问题的一些信息,以改善此答案。 (5认同)
  • 只是为了明确它们是相同的,所以它或对吗? (4认同)

kev*_*ite 5

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

var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;
Run Code Online (Sandbox Code Playgroud)