Get file name from a path string in C#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?

How to extract the filename from a path

string filename = System.IO.Path.GetFileName("/Images/She.jpg");

This will work, as long as you don't have anything too complicated in your path, e.g. query parameters after the file name.


Use System.IO.Directory.GetFiles

var files = System.IO.Directory.GetFiles(

Use Path.GetFileName Path.GetFileNameWithoutExtension static methods.

You need using System.IO to do that as well.

string filename = Path.GetFileName(@'C:\Sys\Axa_Excel\Axa123.xlsx');
string filenamewithoutextension = Path.GetFileNameWithoutExtension(@'C:\Sys\Axa_Excel\Axa123.xlsx');