Remove extension from a file name in C#
This post will discuss how to remove an extension from a file name in C#.
1. Using Path.ChangeExtension() method
To get the full path without the extension, consider using Path.ChangeExtension() method. It takes two parameters – the path to modify and the new extension. The idea is to pass null to the ChangeExtension() method parameter to remove the existing extension.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.IO; public class Example { public static void Main() { string filepath = @"C:\some\path\filename.txt"; string filePathWithoutExt = Path.ChangeExtension(filepath, null); Console.WriteLine(filePathWithoutExt); } } /* Output: C:\some\path\filename */ |
2. Using Path.GetExtension() method
The idea is to get the extension name using the Path.GetExtension() method and remove the same characters from the end of the string as the extension’s length.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.IO; public class Example { public static void Main() { string filepath = "D:\Study\filename.txt"; string extension = Path.GetExtension(filepath); string filePathWithoutExt = filepath.Substring(0, filepath.Length - extension.Length); Console.WriteLine(filePathWithoutExt); } } /* Output: C:\some\path\filename */ |
3. Using Path.GetFileNameWithoutExtension() method
If only the file name is needed without path information and the extension, consider using Path.GetFileNameWithoutExtension() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.IO; public class Example { public static void Main() { string filepath = @"C:\some\path\filename.txt"; string fileNameWithoutExt = Path.GetFileNameWithoutExtension(filepath); Console.WriteLine(fileNameWithoutExt); } } /* Output: filename */ |
That’s all about removing the extension from a file name 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 :)