Remove file extension from a file name string
If I have a string saying "abc.txt"
, is there a quick way to get a substring that is just "abc"
?
I can't do an fileName.IndexOf('.')
because the file name could be "abc.123.txt"
or something and I obviously just want to get rid of the extension (i.e. "abc.123"
).
Solution 1:
The Path.GetFileNameWithoutExtension
method gives you the filename you pass as an argument without the extension, as should be obvious from the name.
Solution 2:
There's a method in the framework for this purpose, which will keep the full path except for the extension.
System.IO.Path.ChangeExtension(path, null);
If only file name is needed, use
System.IO.Path.GetFileNameWithoutExtension(path);
Solution 3:
You can use
string extension = System.IO.Path.GetExtension(filename);
And then remove the extension manually:
string result = filename.Substring(0, filename.Length - extension.Length);
Solution 4:
String.LastIndexOf would work.
string fileName= "abc.123.txt";
int fileExtPos = fileName.LastIndexOf(".");
if (fileExtPos >= 0 )
fileName= fileName.Substring(0, fileExtPos);
Solution 5:
If you want to create full path without extension you can do something like this:
Path.Combine( Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath))
but I'm looking for simpler way to do that. Does anyone have any idea?