# How to remove file extension using C#?

I am trying to remove file extension of a file with many dots in it:

string a = "asdasdasd.asdas.adas.asdasdasdasd.edasdasd";

string b = a.Substring(a.LastIndexOf('.'), a.Length - a.LastIndexOf('.'));

string c = a.Replace(b, "");

Console.WriteLine(c);


Is there any better way of doing this?

• Googling this exact question title yields this Stack Overflow answer as the first search result... Apr 7 '14 at 15:32
• are you doing this for practice?
– Malachi
Apr 7 '14 at 15:37
• Please people, for the next time don't answer this question, close it for migratation. This site is codereview, not stackoverflow. Apr 7 '14 at 17:47
• Can a contain a path? Apr 7 '14 at 18:36
• @Manu343726 I don't really like this question, but it does not need to be migrate IMO. We should migrate good question, not borderline question. Apr 7 '14 at 18:36

If you can, just use Path.GetFileNameWithoutExtension

Returns the file name of the specified path string without the extension.

Path.GetFileNameWithoutExtension("asdasdasd.asdas.adas.asdasdasdasd.edasdasd");


With one line of code you can get the same result.

If you want to create one by yourself, why not just use this?

int index = a.LastIndexOf('.');
b = index == -1 ? a : a.Substring(0, index);


P.S Special thanks to @Anthony and @CompuChip to point me out some mistake i done, bad day maybe.

You take everything which comes from 0 (the start) to the last dot which means the start of the extension

• Just note that b = a.Substring(0, a.LastIndexOf('.')); will break on files without an extension because it will end up calling a.Substring(0, -1). Apr 7 '14 at 16:00
• @Anthony Fixed :) Apr 7 '14 at 16:01
• And saving a call to Substring when it is unnecessary: b = index == -1 ? a : a.Substring(0, index); Apr 7 '14 at 16:22
• Thanks to you too @CompuChip, would be great to give to you an upvote but... :| Apr 7 '14 at 16:32
• It's important to note that Path.Path.GetFileNameWithoutExtension removes the path portion of the input. e.g. Path.Path.GetFileNameWithoutExtension("a\b.c") returns "b" not "a\b". Apr 7 '14 at 18:40

Use the Path class within the namespace System.IO.

Path.GetFileNameWithoutExtension(a);


In your code, you are getting the subsection of the extension, then removing it from the original. Instead you should simply just get the subsection of the string without the extension.

string c = a.Substring(0, a.LastIndexOf('.'));


Edit: Just as stated before me by Marco :D

• Downvoted, why? Apr 7 '14 at 17:06
• What happens if the filename doesn't have any .extension? Apr 8 '14 at 10:51
• @200_success It borks, however the parameter of this question is that this path has multiple dots in it. I simply took shortcuts to improve the posted code. I did not go into depth about error checking. Apr 8 '14 at 12:06