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().
Input : string strPath = "c://myfiles//ref//file1.txt"; //function call to get the filename filename = Path.GetFileName(strPath); Output : file1.txt
Filename = file1.txt
- Check if a path has a file name extension in C#
- How to set the Size of the FlowLayoutPanel in C#?
- How to set the Auto Size Mode of FlowLayoutPanel in C#?
- How to set Font in FlowLayoutPanel in C#?
- How to set the Location of the FlowLayoutPanel in C#?
- How to set a Check Box in the DateTimePicker in C#?
- How to style the Border of the FlowLayoutPanel in C#?
- How to set the Name of FlowLayoutPanel in C#?
- How to Style the Border of the RichTextBox in C#?
- How to set the Visibility of the FlowLayoutPanel in C#?
- How to set the Flow Direction of FlowLayoutPanel in C#?
- How to set the Size of the RichTextBox in C#?
- How to set Up and Down Button in DateTimePicker in C#?
- How to set Foreground Color of FlowLayoutPanel in C#?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.