简体   繁体   中英

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:\\xxxx\\xxxx\\xxxx\\abc.pdf". But i want only the file name ie. abc.pdf. How it will get by using string functions?

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.

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'

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

使用System.IO.Path的方法,尤其是Path.GetFileName

System.IO.Path.GetFilename(yourFilename) 将返回文件的名称。

You could use:

System.IO.Path.GetFileNameWithoutExtension("C:\xxxx\xxxx\xxxx\abc.pdf")

And you would get back abc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM