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.pdf. How it will get by using string functions?
6 Answers
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.
1 Comment
Use the Path.GetFileName() Method
(Edited) sample from the MSDN-page:
string fileName = @"C:\xxxx\xxxx\xxxx\abc.pdf";
string path = @"C:\xxxx\xxxx\xxxx\";
string path2 = @"C:\xxxx\xxxx\xxxx";
string result;
result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
result = Path.GetFileName(path2);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path2, result);
This code produces output similar to the following:
GetFileName('C:\xxxx\xxxx\xxxx\abc.pdf') returns 'abc.pdf'
GetFileName('C:\xxxx\xxxx\xxxx\') returns ''
GetFileName('C:\xxxx\xxxx\xxxx') returns 'xxxx'
Comments
Sytem.IO.FileInfo is also quite cool:
In your case you can do
FileInfo fi = new FileInfo("C:\xxxx\xxxx\xxxx\abc.pdf");
string name = fi.Name; // it gives you abc.pdf
Then you can have several other pieces of information:
does the file really exist? fi.Exists gives you the answer
what's its extension? see fi.Extension
what's the name of its directory? see fi.Directory
etc.
Have a look at all the members of FileInfo you may find something interesting for your needs