string path = "C:\folder1\folder2\file.txt";
我可以使用什么对象或方法来给我结果文件夹2?
string path = "C:\folder1\folder2\file.txt";
我可以使用什么对象或方法来给我结果文件夹2?
当前回答
另一种方法是分割路径,使用c# 8.0中引入的Index Struct从路径中获取倒数第二个元素。
var path = @"C:\folder1\folder2\file.txt";
var folder = path.Split(@"\")[^2]; // 2nd element from the end
Console.WriteLine(folder); // folder2
其他回答
另一种方法是分割路径,使用c# 8.0中引入的Index Struct从路径中获取倒数第二个元素。
var path = @"C:\folder1\folder2\file.txt";
var folder = path.Split(@"\")[^2]; // 2nd element from the end
Console.WriteLine(folder); // folder2
试试这个:
string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;
当路径中没有文件名时,我使用下面的代码片段获取路径的目录:
例如“c:\tmp\test\visual”;
string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));
输出:
视觉
简单干净。只使用System.IO.FileSystem -就像一个魅力:
string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;
string Folder = Directory.GetParent(path).Name;