Get the (last part of) current directory name in C#

后端 未结 10 591
灰色年华
灰色年华 2020-12-08 08:48

I need to get the last part of current directory, for example from /Users/smcho/filegen_from_directory/AIRPassthrough, I need to get AIRPassthrough

相关标签:
10条回答
  • 2020-12-08 09:32

    rather then using the '/' for the call to split, better to use the Path.DirectorySeparatorChar :

    like so:

    path.split(Path.DirectorySeparatorChar).Last() 
    
    0 讨论(0)
  • 2020-12-08 09:33

    Well, to exactly answer your question title :-)

    var lastPartOfCurrentDirectoryName = 
       Path.GetFileName(Environment.CurrentDirectory);
    
    0 讨论(0)
  • 2020-12-08 09:41

    You can also use the Uri class.

    new Uri("file:///Users/smcho/filegen_from_directory/AIRPassthrough").Segments.Last()
    

    You may prefer to use this class if you want to get some other segment, or if you want to do the same thing with a web address.

    0 讨论(0)
  • 2020-12-08 09:42
    var lastFolderName = Path.GetFileName(
        path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
    

    This works if the path happens to contain forward slash separators or backslash separators.

    0 讨论(0)
提交回复
热议问题