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

后端 未结 10 590
灰色年华
灰色年华 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:20

    You could try:

    var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
    var dirName = new DirectoryInfo(path).Name;
    
    0 讨论(0)
  • 2020-12-08 09:26

    You're looking for Path.GetFileName.
    Note that this won't work if the path ends in a \.

    0 讨论(0)
  • 2020-12-08 09:26

    This is a slightly different answer, depending on what you have. If you have a list of files and need to get the name of the last directory that the file is in you can do this:

    string path = "/attachments/1828_clientid/2938_parentid/somefiles.docx";
    string result = new DirectoryInfo(path).Parent.Name;
    

    This will return "2938_parentid"

    0 讨论(0)
  • 2020-12-08 09:27

    Try this:

    String newString = "";
    Sting oldString = "/Users/smcho/filegen_from_directory/AIRPassthrough";
    
    int indexOfLastSlash = oldString.LastIndexOf('/', 0, oldString.length());
    
    newString = oldString.subString(indexOfLastSlash, oldString.length());
    

    Code may be off (I haven't tested it) but the idea should work

    0 讨论(0)
  • 2020-12-08 09:27

    This works perfectly fine with me :)

    Path.GetFileName(path.TrimEnd('\\')
    
    0 讨论(0)
  • 2020-12-08 09:28

    You can try below code :

    Path.GetFileName(userpath)

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