Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 269
AdamMc331 Avatar asked Nov 19 '14 14:11

AdamMc331


People also ask

How do I get the last part of a path?

The first strips off any trailing slashes, the second gives you the last part of the path. Using only basename gives everything after the last slash, which in this case is '' . I initially thought rstrip('/') would be simpler but then quickly realised I'd have to use rstrip(os.

How do I get the last part of a path in Python?

split() This method uses os. path. split() to find the last part of the path.

How can I get the last part of a path in PHP?

To get the trailing name component of a path you should use basename! In case your path is something like $str = "this/is/something/" the end(explode($str)); combo will fail.

How do I get the last directory name in Unix?

How do I get directory name from its path on a Linux or Unix-like system? [/donotprint]In other words, you can extract the directory name using dirname command.


1 Answers

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)

like image 74
Habib Avatar answered Oct 06 '22 00:10

Habib