Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Could you help me for finding the file name from the string. Now i have one string of content like "C:xxxxxxxxxxxxabc.pdf". But i want only the file name ie. abc.pdf. How it will get by using string functions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use Path.GetFileName:

string full = @"C:xxxxxxxxxxxxabc.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:WindowsSystem32" it would claim a filename of System32, even though that's actually a directory. (Passing in "C:WindowsSystem32" 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:fooaraz.txt" and it would return baz.txt even if foo and bar don't exist.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...