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
As the name implies, the Path.GetFileNameWithoutExtension function returns the filename you pass as an argument without the extension.
Answered by R. Martinho Fernandes
The framework has a method for this that will keep the entire path except for the extension.
Use if only the file name is required.
Answered by Ran QUAN
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
String.LastIndexOf would work.
string fileName= "abc.123.txt"; int fileExtPos = fileName.LastIndexOf("."); if (fileExtPos >= 0 ) fileName= fileName.Substring(0, fileExtPos);
Answered by Andrew
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 https://stackoverflow.com/questions/7356205/remove-file-extension-from-a-file-name-string