How can I get directory name of a path?

2019-08-29 09:13发布

问题:

I tried using Path.GetDirectoryName() but it doesn't work.

What I'm trying to get is from /home/nubela/test/some_folder , I wanna get "some_folder"

How can I do this? The method should work for both Windows/Linux (Mono)

Thanks!

回答1:

If you have the path as a string already you can use this method to extract the lowest level directory:

String dir
    = yourPath.Substring(
          yourPath.LastIndexOf(Path.DirectorySeparatorChar) + 1);

Since this code uses Path.DirectorySeparatorChar it is platform independent.



回答2:

Use Path.GetFileName instead? These functions work just on the string you provide and don't care if it's a directory or a file path.



回答3:

My first idea would be to use System.IO.Path.GetDirectoryName, too. But you can try a regular expression to get the final substring of your string. Here is an answer in StackOverflow, using regular expressiones, that answers this.



标签: c# mono