How can I get the last folder from a path string?

后端 未结 3 444
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 00:12

I have a directory that looks something like this:

C:\\Users\\me\\Projects\\

In my application, I append to that path a given project name:

3条回答
  •  甜味超标
    2020-12-11 00:47

    If you're a Linq addict like me, you may enjoy this. Works regardless of the termination of the path string.

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

    Example Usage:

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

    Output: etc

提交回复
热议问题