How to get file extension using .NET c#
By doitex
Function GetFileExtension below is writen in .NET c# and it's main purpose is to extract file extension from given file name, for example, "my_file_name.doc" will return "doc".
Function supports multi dots in file names, for example, "my_file.with.several.dots.txt" will return "txt".
If some error, for example, no file name or no dot in file name, then function returns empty string.
The file extension is returned in lower case.
private string GetFileExtension(string sFileName)
{
sFileName = sFileName.Trim();
if (String.IsNullOrEmpty(sFileName))
{
return String.Empty;
}
string sExtension = String.Empty;
char[] cArr = sFileName.ToCharArray();
int iIndex = 0;
for (int i = cArr.Length - 1; i > -1; i--)
{
if (cArr[i].Equals('.'))
{
iIndex = i;
break;
}
}
if (iIndex > 0)
{
for (int i = iIndex + 1; i < cArr.Length; i++)
{
sExtension += cArr[i];
}
}
return sExtension.ToLower();
}You can double click on code block abowe and then Copy+Paste in your project.
Happy programming!
Comments
No comments yet.