Skip to content
Related Articles

Related Articles

How to Extract filename from a given path in C#
  • Last Updated : 04 Apr, 2019

While developing an application that can be desktop or web in C#, such kind of requirement to extract the filename from a given path (where the path can be taken while selecting a file using File Open dialog box or any other sources) can arise. A path may contain the drive name, directory name(s) and the filename. To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.

Syntax: public static string GetFileName (string path);
Here, path is the string from which we have to obtain the file name and extension.

Return Value: This method will return the characters after the last directory separator character in path. If the last character of the path is a directory or volume separator character, this method returns Empty. If the path is null, this method returns null.

Exception: This method will give ArgumentException if the path contains one or more of the invalid characters defined in GetInvalidPathChars().

Examples:



Input : 

string strPath = "c://myfiles//ref//file1.txt";

//function call to get the filename
filename = Path.GetFileName(strPath);

Output :

file1.txt




// C# program to extract the 
// filename from a given path
using System;
using System.IO;
using System.Text;
  
namespace Geeks {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
  
        // taking full path of a file
        string strPath = "C:// myfiles//ref//file1.txt";
  
        // initialize the value of filename
        string filename = null;
  
        // using the method
        filename = Path.GetFileName(strPath);
        Console.WriteLine("Filename = " + filename);
  
        Console.ReadLine();
    }
}
}
Output:
Filename = file1.txt

Reference:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :