Ash*_*nko 169 c# filesystems path
string path = "C:/folder1/folder2/file.txt";
Run Code Online (Sandbox Code Playgroud)
我可以使用哪些对象或方法来获得结果folder2?
LBu*_*kin 302
我可能会使用类似的东西:
string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );
Run Code Online (Sandbox Code Playgroud)
内部调用GetDirectoryName将返回完整路径,而外部调用GetFileName()将返回最后一个路径组件 - 这将是文件夹名称.
无论路径是否实际存在,此方法都有效.然而,这种方法依赖于最初以文件名结尾的路径.如果不知道路径是以文件名还是文件夹名结尾 - 那么它需要您检查实际路径以查看该位置是否存在文件/文件夹.在这种情况下,Dan Dimitru的回答可能更合适.
Wah*_*hyu 31
试试这个:
string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;
Run Code Online (Sandbox Code Playgroud)
sus*_*oo_ 16
简单干净.只使用System.IO.FileSystem- 像魅力一样:
string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;
Run Code Online (Sandbox Code Playgroud)
DirectoryInfo执行剥离目录名称的工作
string my_path = @"C:\Windows\System32";
DirectoryInfo dir_info = new DirectoryInfo(my_path);
string directory = dir_info.Name; // System32
Run Code Online (Sandbox Code Playgroud)
当路径中没有文件名时,我使用此代码片段获取路径的目录:
例如"c:\ tmp\test\visual";
string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));
Run Code Online (Sandbox Code Playgroud)
输出:
视觉
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
218181 次 |
| 最近记录: |