Get File Name From the Path in C#

Minahil Noor Feb 28, 2021
Get File Name From the Path in C#

This article will introduce a method to get the file name from a given path in C#.

Use the GetFileName() Method to Extract File Name From a Given Path in C#

We will use the GetFileName() method to extract file name from a given path in C#. This method extracts the file name from the passed path. The correct syntax to use this method is as follows.

Path.GetFileName(string path);

This method returns the name of the file.

The program below shows how we can use the GetFileName() method to extract file name from a given path.

using System; 
using System.IO; 
using System.Text; 
  
class FileName {
    static void Main(string[] args) 
    {
        string path = "E://Jinku Hu//Starting Over//Csharp//myfile.md"; 
        string filename = null; 
        filename = Path.GetFileName(path); 
        Console.WriteLine("Filename = " + filename); 
        Console.ReadLine(); 
    } 
} 

Output:

Filename = myfile.md

Related Article - Csharp File