get directory from full path

前端 未结 10 1383
慢半拍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:48

    Just use:

    string dirname = new DirectoryInfo(@"C:\temp\foo\bar\").Name;      
    

    According to MSDN this returns the name of the directory, not the full path.

    Link to MSDN Library

    Hope this helps.........

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

    I can think of 4 ways instantly

    1

    • If the string ends with a slash remove it
    • Use Path.GetFilename (or numerous other System.IO methods)

    2

    • Split the string on slashes into an array
    • Get the last index of the array

    3

    • Create a Uri class with it in the constructor
    • Use the Segments property

    4

    • The linq way someone mentioned above
    0 讨论(0)
  • 2021-01-01 12:52

    Try this

    string DirName = System.IO.Directory.GetParent(@"C:\temp\foo\bar\").Name;
    
    0 讨论(0)
  • 2021-01-01 12:53

    It looks like a bunch of people have withdrawn their answers, which is possibly a shame.

    This one's got to be worth stating, only for the "teach a man to fish" quality of it - it's short, elegant and made of two separate things that, once learned, can be re-applied to other problems.

    string lastPiece = wholePath.Split('\\').Last();
    

    Last will throw if the list is empty.

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