c# remove extension from filename

c# remove extension from filename

You can remove the extension from a filename in C# using several methods. Here are a couple of common approaches:

Using Path.GetFileNameWithoutExtension Method:

You can use the Path.GetFileNameWithoutExtension method from the System.IO namespace to get the filename without the extension.



using System.IO;


string fileName = "example.txt";


string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);


Console.WriteLine(fileNameWithoutExtension); // Output: example

Using Substring Method:

You can also achieve this using string manipulation, extracting the substring before the last dot (.) occurrence.



string fileName = "example.txt";


int index = fileName.LastIndexOf('.');


string fileNameWithoutExtension = index == -1 ? fileName : fileName.Substring(0, index);


Console.WriteLine(fileNameWithoutExtension); // Output: example

Both methods will give you the filename without the extension. Choose the one that best suits your needs and coding style.