EN
C# / .NET - get file extension
7
points
In C# / .NET it is possible to get file extension from path in following way.
1. Path.GetExtension
method example
string path = @"C:\path\to\file.txt";
string extension = Path.GetExtension(path);
Console.WriteLine("File extension: " + extension);
Output:
File extension: .txt
2. String.LastIndexOf
method example
public class PathUtils
{
private static char[] DELIMITERS = new char[] { '\\', '/' };
public static string GetFilename(string path)
{
int index = path.LastIndexOfAny(DELIMITERS);
if (index == -1)
return path;
return path.Substring(index + 1);
}
public static string GetExtension(string path)
{
string name = GetFilename(path);
int index = name.LastIndexOf(".");
if (index == -1)
return "";
if (index == name.Length - 1)
return "";
return name.Substring(index);
}
}
Example:
string path = @"C:\path\to\file.txt";
string extension = PathUtils.GetExtension(path);
Console.WriteLine("File extension: " + extension);
Output:
File extension: .txt
3. Regex.Match
method example
public class PathUtils
{
private static Regex REGEX = new Regex(@"(\.[^.\/]+)$");
public static string GetExtension(string path)
{
Match match = REGEX.Match(path);
foreach(Group entry in match.Groups)
return entry.Value;
return "";
}
}
Example:
string path = @"C:\path\to\file.txt";
string extension = PathUtils.GetExtension(path);
Console.WriteLine("File extension: " + extension);
Output:
File extension: .txt