get directory from full path

前端 未结 10 1337
慢半拍i
慢半拍i 2021-01-01 11:54

If i have:

C:\\temp\\foo\\bar\\

(NOTE: bar is a directory)

how can i parse out:

bar

相关标签:
10条回答
  • 2021-01-01 12:31
    string dirname = new DirectoryInfo(path).Name;  
    Console.WriteLine(dirname);   
    
    0 讨论(0)
  • 2021-01-01 12:34

    I figured it out.

    DirectoryInfo info = new DirectoryInfo(sourceDirectory_);
    string currentDirectoryName = info.Name;
    
    0 讨论(0)
  • 2021-01-01 12:34

    Try

    System.IO.Path.GetFileName("C:\\temp\\foo\\bar");
    
    0 讨论(0)
  • 2021-01-01 12:34

    In Unix this is known as the basename, a quick google came up with this link for a C# version. I'm sure there are others ...

    0 讨论(0)
  • 2021-01-01 12:44

    The simplest way to do this without creating a new DirectoryInfo instance is to use the Path.GetFileName static method. This is located in System.IO.

    using System.IO;
    
    string lastFolderName = Path.GetFileName(@"C:\Folder1\Folder2");
    

    The variable would be set to "Folder2".

    This is quite a bit more efficient that creating a new instance of the DirectoryInfo class!

    0 讨论(0)
  • 2021-01-01 12:44

    if the answers above do not satisfy your needs, why not just substring the string from the last .

    string dirName = originalDirName.Substring(originalDirName.LastIndexOf("\\") + 1);
    

    sure, you should do some checking if the originalDirName does not end on a \ and if the originalDirName is longer than zero and actually contains \ characters.

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