string path = "C:\folder1\folder2\file.txt";
我可以使用什么对象或方法来给我结果文件夹2?
string path = "C:\folder1\folder2\file.txt";
我可以使用什么对象或方法来给我结果文件夹2?
当前回答
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
其他回答
简单干净。只使用System.IO.FileSystem -就像一个魅力:
string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
DirectoryInfo执行剥离目录名的工作
string my_path = @"C:\Windows\System32";
DirectoryInfo dir_info = new DirectoryInfo(my_path);
string directory = dir_info.Name; // System32
这很难看,但避免了分配:
private static string GetFolderName(string path)
{
var end = -1;
for (var i = path.Length; --i >= 0;)
{
var ch = path[i];
if (ch == System.IO.Path.DirectorySeparatorChar ||
ch == System.IO.Path.AltDirectorySeparatorChar ||
ch == System.IO.Path.VolumeSeparatorChar)
{
if (end > 0)
{
return path.Substring(i + 1, end - i - 1);
}
end = i;
}
}
if (end > 0)
{
return path.Substring(0, end);
}
return path;
}
试试这个:
string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;