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
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp File

  • Rename a File in C#
  • Download a File From a URL in C#
  • C# Read a Text File Line by Line