Getting File name from the String

后端 未结 5 581
醉话见心
醉话见心 2021-01-20 11:29

Could you help me for finding the file name from the string. Now i have one string of content like \"C:\\xxxx\\xxxx\\xxxx\\abc.pdf\". But i want only the file name ie. abc.p

5条回答
  •  不知归路
    2021-01-20 11:48

    Use Path.GetFileName:

    string full = @"C:\xxxx\xxxx\xxxx\abc.pdf";
    string file = Path.GetFileName(full);
    Console.WriteLine(file); // abc.pdf
    

    Note that this assumes the last part of the name is a file - it doesn't check. So if you gave it "C:\Windows\System32" it would claim a filename of System32, even though that's actually a directory. (Passing in "C:\Windows\System32\" would return an empty string, however.) You can use File.Exists to check that a file exists and is a file rather than a directory if that would help.

    This method also doesn't check that all the other elements in the directory hierarchy exist - so you could pass in "C:\foo\bar\baz.txt" and it would return baz.txt even if foo and bar don't exist.

提交回复
热议问题