Get File Name From the Path in C#

How to Get the File Path of any Fil...
How to Get the File Path of any File or Folder on Mac OS

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

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