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

别等时光非礼了梦想. 提交于 2019-11-27 07:34:58

问题


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:

C:\Users\me\Projects\myProject

After, I want to be able to pass that into a method. Inside this method I would also like to use the project name. What is the best way to parse the path string to get the last folder name?

I know a work-around would be to pass the path and the project name into the function, but I was hoping I could limit it to one parameter.


回答1:


You can do:

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

Or use Path.GetFileName like (with a bit of hack):

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

Path.GetFileName returns the file name from the path, if the path is terminating with \ then it would return an empty string, that is why I have used TrimEnd(Path.DirectorySeparatorChar)




回答2:


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

result = myProject




回答3:


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



来源:https://stackoverflow.com/questions/27019082/how-can-i-get-the-last-folder-from-a-path-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!