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(
/// <summary>
/// Get the extension from the given filename
/// </summary>
/// <param name="fileName">the given filename ie:abc.123.txt</param>
/// <returns>the extension ie:txt</returns>
public static string GetFileExtension(this string fileName)
{
string ext = string.Empty;
int fileExtPos = fileName.LastIndexOf(".", StringComparison.Ordinal);
if (fileExtPos >= 0)
ext = fileName.Substring(fileExtPos, fileName.Length - fileExtPos);
return ext;
}
This implementation should work.
string file = "abc.txt";
string fileNoExtension = file.Replace(".txt", "");
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);
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?
You maybe not asking the UWP api.
But in UWP, file.DisplayName
is the name without extensions. Hope useful for others.
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);