Get file name from a path string in C#



fileName = Path.GetFileName (path);


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?

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

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

Try this:

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

This will return "hello" for fileName.