从完整的文件名路径中获取文件夹名称

260
string path = "C:\folder1\folder2\file.txt";

有哪些对象或方法可以使我获得结果folder2


5
你想要最后一个文件夹的名称,所以如果你有C:\folder1\folder2\folder3\file.txt,你想要"folder3"吗? - Steve Danner
12个回答

431

我可能会使用类似这样的东西:

string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );

调用GetDirectoryName方法会返回完整路径,而调用GetFileName()方法会返回最后一个路径组成部分——这将是文件夹名。

该方法适用于路径是否实际存在的情况。但是,该方法需要路径最初以文件名结尾。如果不知道路径是以文件名还是文件夹名结尾,则需要先检查实际路径以查看位置上是否存在文件/文件夹。在这种情况下,Dan Dimitru的答案可能更为合适。


196
另一种解决方案: 返回fullPath所指路径的目录名称,可以使用以下代码:return new DirectoryInfo(fullPath).Name; - Davide Icardi
7
你的评论真应该作为答案,它很有价值。 - Ondrej Janacek
5
当路径不包含文件(即目录路径)时,此方法无效,而@DavideIcardi的解决方案则有效。 - Aage
2
有趣的是,如果路径是"C:/folder1/folder2./file.txt"(注意folder2末尾的点),结果将是“folder2”,而不是“folder2.”(这是一个完全有效的文件夹名称)。 - Claudiu Constantin
14
警告:这个解决方法是错误的!对于 "C:/bin/logs",它返回 "bin"。请使用 return new DirectoryInfo(fullPath).Name; 替代。 - Chris W
显示剩余3条评论

59

试一下这个:

string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;

1
这是更好的答案,因为它实际上返回了OP问题中要求的确切结果。谢谢。 - Taylor Brown

37

简单而干净。仅使用 System.IO.FileSystem - 运行得很好:

string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;

11
在这种情况下,“folder”指的是“file.txt”,而不是“folder2”。 - TJ Rockefeller

30

DirectoryInfo的作用是去除目录名

string my_path = @"C:\Windows\System32";
DirectoryInfo dir_info = new DirectoryInfo(my_path);
string directory = dir_info.Name;  // System32

11
我使用这段代码片段来获取没有文件名的路径所在的目录:
例如 "c:\tmp\test\visual";
string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));

输出:

可视化的


2
你可以直接使用 Path.GetFileName(dir) 方法,它会很好地返回文件夹名称。 - jrich523

8
string Folder = Directory.GetParent(path).Name;

5
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();

在其他平台上,硬编码目录分隔符(\)是行不通的。请使用Path.DirectorySeparatorChar或至少使用在Unix系统上有效且在Windows中作为替代分隔符的斜杠(/)。 - undefined

2

需要注意的是,在循环中获取目录名称列表时,DirectoryInfo类只会初始化一次,因此只允许第一次调用。为了避免这种限制,请确保在循环内使用变量存储任何单个目录的名称。

例如,此示例代码循环遍历父目录中的目录列表,同时将找到的每个目录名称添加到字符串类型的List中:

[C#]

string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();

foreach (var directory in parentDirectory)
{
    // Notice I've created a DirectoryInfo variable.
    DirectoryInfo dirInfo = new DirectoryInfo(directory);

    // And likewise a name variable for storing the name.
    // If this is not added, only the first directory will
    // be captured in the loop; the rest won't.
    string name = dirInfo.Name;

    // Finally we add the directory name to our defined List.
    directories.Add(name);
}

[VB.NET]

Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()

For Each directory In parentDirectory

    ' Notice I've created a DirectoryInfo variable.
    Dim dirInfo As New DirectoryInfo(directory)

    ' And likewise a name variable for storing the name.
    ' If this is not added, only the first directory will
    ' be captured in the loop; the rest won't.
    Dim name As String = dirInfo.Name

    ' Finally we add the directory name to our defined List.
    directories.Add(name)

Next directory

0

以下代码可帮助获取文件夹名称

public ObservableCollection items = new ObservableCollection();
try { string[] folderPaths = Directory.GetDirectories(stemp); items.Clear(); foreach (string s in folderPaths) { items.Add(new gridItems { foldername = s.Remove(0, s.LastIndexOf('\\') + 1), folderpath = s }); } } catch (Exception a) {
} public class gridItems { public string foldername { get; set; } public string folderpath { get; set; } }

0

另一种方法是使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接