获取文件的最高路径

时间:2018-06-04 13:29:46

标签: c# path

我有一条像

这样的路径
string path = @"C:\foo\bar\temp\test\file.txt";

并希望获取文件的foldername - 在这种情况下,预期结果为"test"

path.SubString(path.LastIndexOf('/')等相比,是否存在更优雅的构建方式。

4 个答案:

答案 0 :(得分:3)

您必须使用Path.GetDirectoryName (path);

string path = "C:/foo/bar/yourFile.txt";
string folderName = Path.GetFileName(Path.GetDirectoryName(path));

OR

string path = "C:/foo/bar/yourFile.txt";
string folderName = new DirectoryInfo(path).Name;

OR

string path = "C:/foo/bar/yourFile.txt";
string folderName = new FileInfo(path).Directory?.Name;

更多信息: https://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx

答案 1 :(得分:2)

您可以使用DirectoryInfo.Name获取文件的父目录名称:

new FileInfo(@"C:\foo\bar\temp\test\file.txt").Directory.Name

这将返回' test'从例子中。

答案 2 :(得分:1)

使用the static Path class

Path.GetFileName(Path.GetDirectoryName(path))

答案 3 :(得分:0)

您应该使用Path.GetDirectoryName(),然后选择Path.GetFileName()

此示例返回您要求的内容:

var fileName = @"C:\foo\bar\temp\test\file.txt";
var directoryPath = Path.GetDirectoryName(fileName);
var directoryName = Path.GetFileName(directoryPath); 
Console.WriteLine(directoryName);

结果:测试