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:21

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

查看更多
大哥的爱人
4楼-- · 2019-01-01 01:30

Try this:

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

This will return "hello" for fileName.

查看更多
登录 后发表回答