我用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();

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


当前回答

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

其他回答

路径。GetFileName

返回所表示的文件路径的文件名和扩展名 通过只读字符跨度。


路径。GetFileNameWithoutExtension

返回不带文件路径扩展名的文件名 由只读字符跨度表示。


Path类非常棒。

Namespace: using System.IO;  
 //use this to get file name dynamically 
 string filelocation = Properties.Settings.Default.Filelocation;
//use this to get file name statically 
//string filelocation = @"D:\FileDirectory\";
string[] filesname = Directory.GetFiles(filelocation); //for multiple files
    

你在App.config文件中的路径配置如果你要动态获取文件名

    <userSettings>
        <ConsoleApplication13.Properties.Settings>
          <setting name="Filelocation" serializeAs="String">
            <value>D:\\DeleteFileTest</value>
          </setting>
              </ConsoleApplication13.Properties.Settings>
      </userSettings>

你可以像下面这样使用Path API:

 var filenNme = Path.GetFileNameWithoutExtension([File Path]);

更多信息:路径。GetFileNameWithoutExtension

try

System.IO.Path.GetFileNameWithoutExtension(path); 

demo

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);

// This code produces output similar to the following:
//
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
// GetFileName('C:\mydir\') returns ''

https://msdn.microsoft.com/en-gb/library/system.io.path.getfilenamewithoutextension%28v=vs.80%29.aspx

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

string FileName = Location.Substring(Location.LastIndexOf('\\') +
    1);