2012-10-22 33 views
22

Vì vậy, nói tôi cóC# - Làm thế nào để trích xuất tên tập tin và phần mở rộng từ một đường dẫn?

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

Làm thế nào để tôi nhận được chỉ "file.exe"? Tôi đã suy nghĩ một cái gì đó với phân chia (xem bên dưới), nhưng những gì tôi đã cố gắng không hoạt động ...

Đây là mã của tôi.

 List<string> procs = new List<string>(); //Used to check if designated process is already running 
     foreach (Process prcs in Process.GetProcesses()) 
      procs.Add(prcs.ProcessName); //Add each process to the list 
     foreach (string l in File.ReadAllLines("MultiStart.txt")) //Get list of processes (full path) 
      if (!l.StartsWith("//")) //Check if it's commented out 
       if (!procs.Contains(l.Split('\\')[l.Split('\\').Length - 1])) //Check if process is already running 
        Process.Start(l); 

Tôi có thể chỉ là một noob. ._.

Trả lời

15

Bạn đang tìm kiếm Path.GetFileName(string).

+0

Mã của tôi cần Path.GetFileNameWithoutExtension, nhưng cảm ơn ... – CrimsonDeath

+5

Đó không phải là những gì yo câu hỏi ur nói, mặc dù. – Joey

78

System.IO có các lớp khác nhau để làm việc với tệp và thư mục. Giữa chúng, một trong những người hữu ích nhất là Path trong đó có rất nhiều phương pháp helper tĩnh để làm việc với các tập tin và thư mục:

Path.GetExtension(yourPath); // returns .exe 
Path.GetFileNameWithoutExtension(yourPath); // returns File 
Path.GetFileName(yourPath); // returns File.exe 
Path.GetDirectoryName(yourPath); // returns C:\Program Files\Program 
+4

Và 'Path.GetDirectoryName (yourPath)' sẽ tìm nạp đường dẫn thư mục. –

2

Với việc tìm kiếm nhân vật cuối cùng bạn có thể nhận được kết quả đúng.

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 Tên: fatih.gurdal

Full File Extension: docx

Các vấn đề liên quan