Getting File name from the String

后端 未结 5 569
醉话见心
醉话见心 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:40

    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

    0 讨论(0)
  • 2021-01-20 11:40

    System.IO.Path.GetFilename(yourFilename) will return the name of the file.

    0 讨论(0)
  • 2021-01-20 11:41

    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'
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-20 11:57

    Use the methods of System.IO.Path, especially Path.GetFileName.

    0 讨论(0)
提交回复
热议问题