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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13003555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:18:13  来源:igfitidea点击:

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

c#filepath

提问by CrimsonDeath

So, say I have

所以,说我有

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

How do I get only "File.exe"? I was thinking something with split (see below), but what I tried doesn't work...

我如何只获得“File.exe”?我正在考虑拆分(见下文),但我尝试的方法不起作用......

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. ._.

我可能只是个菜鸟。._.

回答by SLaks

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

您正在寻找Path.GetFileName(string).

回答by manman

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

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

回答by Fatih GüRDAL

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

完整文件名:fatih.gurdal.docx

完整文件名称:fatih.gurdal

完整文件扩展名:docx