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.
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.
split() This method uses os. path. split() to find the last part of the path.
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 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With