Coder Perfect

Remove the file extension from a string of file names.


Is there an easy way to retrieve a substring that is only “abc” from a string that says “abc.txt”?

I can’t use fileName.IndexOf(‘.’) since the file name may be something like “abc.123.txt” or something like that, and I obviously just want to get rid of the extension (i.e. “abc.123”).

Asked by meds

Solution #1

As the name implies, the Path.GetFileNameWithoutExtension function returns the filename you pass as an argument without the extension.

Answered by R. Martinho Fernandes

Solution #2

The framework has a method for this that will keep the entire path except for the extension.

System.IO.Path.ChangeExtension(path, null);

Use if only the file name is required.


Answered by Ran QUAN

Solution #3

You can use

string extension = System.IO.Path.GetExtension(filename);

Then manually remove the extension:

string result = filename.Substring(0, filename.Length - extension.Length);

Answered by phdesign

Solution #4

String.LastIndexOf would work.

string fileName= "abc.123.txt";
int fileExtPos = fileName.LastIndexOf(".");
if (fileExtPos >= 0 )
 fileName= fileName.Substring(0, fileExtPos);

Answered by Andrew

Solution #5

You can do something like this to build a whole path without an extension:

Path.Combine( Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath))

However, I’m seeking for a less complicated approach to accomplish this. Is there anyone who knows?

Answered by Logman

Post is based on