如何从路径字符串中获取最后一个文件夹?

问题描述 投票:0回答:4

我有一个看起来像这样的目录:

C:\Users\me\Projects\

在我的应用程序中,我将给定的项目名称附加到该路径:

C:\Users\me\Projects\myProject

之后,我希望能够将其传递到一个方法中。在这个方法中我还想使用项目名称。解析路径字符串以获取最后一个文件夹名称的最佳方法是什么?

我知道一种解决方法是将路径和项目名称传递到函数中,但我希望可以将其限制为一个参数。

c# parsing filepath
4个回答
76
投票

你可以这样做:

string dirName = new DirectoryInfo(@"C:\Users\me\Projects\myProject\").Name;

或者像

一样使用
Path.GetFileName(稍微修改一下)

string dirName2 = Path.GetFileName(
              @"C:\Users\me\Projects\myProject".TrimEnd(Path.DirectorySeparatorChar));

Path.GetFileName
从路径返回文件名,如果路径以
\
结尾,那么它将返回一个空字符串,这就是我使用
TrimEnd(Path.DirectorySeparatorChar)

的原因

3
投票
string path = @"C:\Users\me\Projects\myProject";
string result = System.IO.Path.GetFileName(path);

结果=我的项目


1
投票

如果您像我一样是 Linq 迷,您可能会喜欢这个。无论路径字符串是否终止都有效。

public static class PathExtensions
{
    public static string GetLastPathSegment(this string path)
    {
        string lastPathSegment = path
            .Split(new string[] {@"\"}, StringSplitOptions.RemoveEmptyEntries)
            .LastOrDefault();

        return lastPathSegment;
    }
}

用法示例:

lastSegment = Paths.GetLastPathSegment(@"C:\Windows\System32\drivers\etc");
lastSegment = Paths.GetLastPathSegment(@"C:\Windows\System32\drivers\etc\");

输出: 等等


0
投票

最简单的方法是

dirName = Path.GetFileName(Path.GetDirectoryName(path))
© www.soinside.com 2019 - 2024. All rights reserved.