Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

c# - Getting File name from the String

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...