string path = "C:\folder1\folder2\file.txt";
我可以使用哪些对象或方法来获得folder2
的结果
发布于 2010-09-17 23:03:57
我可能会使用类似这样的东西:
string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );
对GetDirectoryName
的内部调用将返回完整路径,而对GetFileName()
的外部调用将返回最后一个路径组件-即文件夹名称。
无论路径是否实际存在,此方法都有效。但是,这种方法依赖于最初以文件名结尾的路径。如果不知道路径是否以文件名或文件夹名结尾-那么它要求您首先检查实际路径,看看文件/文件夹是否存在于该位置。在这种情况下,Dan Dimitru的答案可能更合适。
发布于 2015-09-18 19:16:58
试试这个:
string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;
发布于 2017-08-15 02:11:38
简单明了。只使用System.IO.FileSystem
-效果很好:
string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;
https://stackoverflow.com/questions/3736462
复制相似问题