How can I get directory name of a path?

左心房为你撑大大i 提交于 2019-12-24 22:31:36

问题


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.



来源:https://stackoverflow.com/questions/2412413/how-can-i-get-directory-name-of-a-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!