我用WPF c#编程。我有如下路径:

C:\Program Files\hello.txt

我想从中提取hello。

路径是从数据库中检索的字符串。目前,我正在使用以下代码通过'\'分割路径,然后再次通过'.'分割:

string path = "C:\\Program Files\\hello.txt";
string[] pathArr = path.Split('\\');
string[] fileArr = pathArr.Last().Split('.');
string fileName = fileArr.Last().ToString();

这是可行的,但我相信应该有更简单、更聪明的解决方案。任何想法?


当前回答

var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);

路径。GetFileNameWithoutExtension

其他回答

var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);

路径。GetFileNameWithoutExtension

string Location = "C:\\Program Files\\hello.txt";

string FileName = Location.Substring(Location.LastIndexOf('\\') +
    1);
string filepath = "C:\\Program Files\\example.txt";
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(filepath);
FileInfo fi = new FileInfo(filepath);
Console.WriteLine(fi.Name);

//input to the "fi" is a full path to the file from "filepath"
//This code will return the fileName from the given path

//output
//example.txt

试试这个:

string fileName = Path.GetFileNameWithoutExtension(@"C:\Program Files\hello.txt");

这将为fileName返回“hello”。

try

fileName = Path.GetFileName (path);

http://msdn.microsoft.com/de-de/library/system.io.path.getfilename.aspx