C# - How to extract the file name and extension from a path?

后端 未结 3 1733
暖寄归人
暖寄归人 2020-12-05 02:45

So, say I have

string path = \"C:\\\\Program Files\\\\Program\\\\File.exe\";

How do I get only \"File.exe\"? I was thinking something with

相关标签:
3条回答
  • 2020-12-05 03:18

    System.IO has different classes to work with files and directories. Between them, one of the most useful one is Path which has lots of static helper methods for working with files and folders:

    Path.GetExtension(yourPath); // returns .exe
    Path.GetFileNameWithoutExtension(yourPath); // returns File
    Path.GetFileName(yourPath); // returns File.exe
    Path.GetDirectoryName(yourPath); // returns C:\Program Files\Program
    
    0 讨论(0)
  • 2020-12-05 03:19

    With the last character search you can get the right result.

    string path = "C:\\Program Files\\Program\\fatih.gurdal.docx";
    string fileName = path.Substring(path.LastIndexOf(((char)92))+ 1);
    int index = fileName.LastIndexOf('.');
    string onyName= fileName.Substring(0, index);
    string fileExtension = fileName.Substring(index + 1);
    Console.WriteLine("Full File Name: "+fileName);
    Console.WriteLine("Full File Ony Name: "+onyName);
    Console.WriteLine("Full File Extension: "+fileExtension);
    

    Output:

    Full File Name: fatih.gurdal.docx

    Full File Ony Name: fatih.gurdal

    Full File Extension: docx

    0 讨论(0)
  • 2020-12-05 03:20

    You're looking for Path.GetFileName(string).

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