从路径获取文件夹名称 [英] Getting the folder name from a path
问题描述
string path = "C:/folder1/folder2/file.txt";
哪些对象或方法可以我使用会给我文件夹2
?
推荐答案
我可能会使用类似:
string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );
到 GetDirectoryName
内调用将返回的完整路径,而外部调用用GetFileName()
将返回最后一个路径组件 - 这将是文件夹名称
The inner call to GetDirectoryName
will return the full path, while the outer call to GetFileName()
will return the last path component - which will be the folder name.
该方法适用的路径是否确实存在。这种做法,确实然而,依赖于文件名结尾最初的道路上。如果它是未知的路径是否在文件名或文件夹名称结尾 - 那么它需要你检查的实际路径,看看文件/文件夹的位置存在第一。在这种情况下,丹Dimitru的回答可能更合适。
This approach works whether or not the path actually exists. This approach, does however, rely on the path initially ending in a filename. If it's unknown whether the path ends in a filename or folder name - then it requires that you check the actual path to see if a file/folder exists at the location first. In that case, Dan Dimitru's answer may be more appropriate.
这篇关于从路径获取文件夹名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!