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

I have a directory that looks something like this:

C:\Users\me\Projects\ 

In my application, I add the name of this project to this path:

 C:\Users\me\Projects\myProject 

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

I know that the workaround should be to pass the path and name of the project to the function, but I was hoping to limit it to one parameter.

+8
c # parsing filepath
source share
2 answers

You can do:

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

Or use Path.GetFileName as (with a little 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 ends with \ , then it returns an empty string, so I have TrimEnd(Path.DirectorySeparatorChar)

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

result = myProject

+1
source share

All Articles