Get file name without extension in C#
This post will discuss how to get a file name without an extension in C#.
1. Using Path.GetFileNameWithoutExtension() method
We can use the Path.GetFileNameWithoutExtension() method to return the file name without the extension. It returns all the characters in the string returned by Path.GetFileName(), minus the last period (.) and the characters following it. Here’s simple usage of this method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.IO; public class Example { public static void Main() { string file = @"C:\image.1.png"; string fileName = Path.GetFileNameWithoutExtension(file); Console.WriteLine(fileName); // image.1 } } |
2. Using Path.GetFileName() method
Similar to the Path.GetFileNameWithoutExtension() method implementation, we can even write our utility method to get the filename without extension. The following example illustrates.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.IO; public class Example { public static string ExtractFileNameWithoutExtention(string path) { string fileName = Path.GetFileName(path); int lastIndex = fileName.LastIndexOf("."); if (lastIndex != -1) { fileName = fileName.Substring(0, lastIndex); } return fileName; } public static void Main() { string path = @"C:\image.1.png"; string fileName = ExtractFileNameWithoutExtention(path); Console.WriteLine(fileName); // image.1 } } |
That’s all about getting the file name without extension in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)