簡體   English   中英

C# - 如何從路徑中提取文件名和擴展名?

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

所以,說我有

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

我如何只獲得“File.exe”? 我正在考慮拆分(見下文),但我嘗試的方法不起作用......

這是我的代碼。

        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);

我可能只是個菜鳥。 ._.

System.IO有不同的類來處理文件和目錄。 在它們之間,最有用的一個是Path ,它有許多用於處理文件和文件夾的靜態輔助方法:

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

您正在尋找Path.GetFileName(string)

通過最后一個字符搜索,您可以獲得正確的結果。

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);

輸出:

完整文件名:fatih.gurdal.docx

完整文件名稱:fatih.gurdal

完整文件擴展名:docx

這對我來說可以在 .extension 之前刪除任何 .sometext

//Remove all extensions "any .sometext.extension" from the file name
var newFileName= Path.GetFileNameWithoutExtension(fileName);
//Combine the the new file name with its actual extension "last .extension"
var fileNameWithExtension = newFileName+ "." + fileName.Split('.')[fileName.Split('.').Length - 1];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM