Get file name from a path string in C#

2019-01-01 00:55发布

I program in WPF C#. I have e.g. the following Path:

C:\Program Files\hello.txt

and I want to output "hello" from it.

The path is a string extract from database. Currently I'm using the following method (split from path by '\' then split again by a '.'):

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

It works, but I believe there should be shorter and smarter solution to that. Any idea?

标签: c#
9条回答
回忆,回不去的记忆
2楼-- · 2019-01-01 01:04
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

Your path configuration in App.config file if you are going to get file name dynamically  -

    <userSettings>
        <ConsoleApplication13.Properties.Settings>
          <setting name="Filelocation" serializeAs="String">
            <value>D:\\DeleteFileTest</value>
          </setting>
              </ConsoleApplication13.Properties.Settings>
      </userSettings>
查看更多
临风纵饮
3楼-- · 2019-01-01 01:06

You can use Path API as follow:

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

More info: Path.GetFileNameWithoutExtension

查看更多
泛滥B
4楼-- · 2019-01-01 01:09

Try this,

string FilePath=@"C:\mydir\myfile.ext";
string Result=Path.GetFileName(FilePath);//With Extension
string Result=Path.GetFileNameWithoutExtension(FilePath);//Without Extension
查看更多
伤终究还是伤i
5楼-- · 2019-01-01 01:12
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);

Path.GetFileNameWithoutExtension

查看更多
公子世无双
6楼-- · 2019-01-01 01:16
string Location = "C:\\Program Files\\hello.txt";

string FileName = Location.Substring(Location.LastIndexOf('\\') +
    1);
查看更多
登录 后发表回答