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

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)

Leave a Comment