简体   繁体   English

C# - 如何从路径中提取文件名和扩展名?

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

So, say I have所以,说我有

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

How do I get only "File.exe"?我如何只获得“File.exe”? I was thinking something with split (see below), but what I tried doesn't work...我正在考虑拆分(见下文),但我尝试的方法不起作用......

This is my code.这是我的代码。

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

I'm probably just being a noob.我可能只是个菜鸟。 ._. ._.

System.IO has different classes to work with files and directories. System.IO有不同的类来处理文件和目录。 Between them, one of the most useful one is Path which has lots of static helper methods for working with files and folders:在它们之间,最有用的一个是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)

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完整文件名:fatih.gurdal.docx

Full File Ony Name: fatih.gurdal完整文件名称:fatih.gurdal

Full File Extension: docx完整文件扩展名:docx

This works for me to remove any .sometext before the .extension这对我来说可以在 .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