Posts

How to Get File Name from Path in C#.Net

How to get only file name with extension and without file extension in c#.net. Here we use Path.GetFileNameWithoutExtension() and Path.GetFileName().
In today's article I will show you show simple tutorial with example how you can get the file name with extension or without extension using C#.net. Path.GetFileNameWithoutExtension() is used to get file name without extension and  Path.GetFileName() is used to get file name with extension. This article you can use in .net core or windows application with c#.net. To demonstrate example, I will use .net core console application. Here is the file for which we are going to get name.

File Name

Get File Name Without Extension in C#.Net

Here we will write code to get the file name without extension using c#.net. 

string path = "C:\\DB\\EmployeeDB.db";
string fileName = Path.GetFileNameWithoutExtension(path);
Console.WriteLine(fileName);
Console.ReadLine(); 
In above code I have declared a variable of string type which is holding the path of the file. In this example I have not validated file exists or not. You must validate file exists or not before performing any file operation. Now let's put a break point and check the output.

File Name Without Extention

Here you can see that we are getting only the file name. Now let's press F5 to print the final output.

File Name in console

Get File Name With Extension in C#.Net

Here we will write code to get the file name with extension using c#.net. 

string path = "C:\\DB\\EmployeeDB.db";
string fileName = Path.GetFileName(path);
Console.WriteLine(fileName);
Console.ReadLine(); 
In above code I have take a variable in string of string type, which is having file path. This variable I have passed in Path.GetFileName(path) to get the file name with extension. As mentioned earlier you must validate your folder and file before performing any operation. Now let's put a break point and run the code to check the output.

File Name With Extension
In above code we can see that the file is having extension. Now press F5 to check the final output.

File with Extension

Post a Comment