EN
C# / .NET - get file extension
7 points
In C# / .NET it is possible to get file extension from path in following way.
xxxxxxxxxx
1
string path = @"C:\path\to\file.txt";
2
3
string extension = Path.GetExtension(path);
4
Console.WriteLine("File extension: " + extension);
Output:
xxxxxxxxxx
1
File extension: .txt
xxxxxxxxxx
1
public class PathUtils
2
{
3
private static char[] DELIMITERS = new char[] { '\\', '/' };
4
5
public static string GetFilename(string path)
6
{
7
int index = path.LastIndexOfAny(DELIMITERS);
8
9
if (index == -1)
10
return path;
11
12
return path.Substring(index + 1);
13
}
14
15
public static string GetExtension(string path)
16
{
17
string name = GetFilename(path);
18
19
int index = name.LastIndexOf(".");
20
21
if (index == -1)
22
return "";
23
24
if (index == name.Length - 1)
25
return "";
26
27
return name.Substring(index);
28
}
29
}
Example:
xxxxxxxxxx
1
string path = @"C:\path\to\file.txt";
2
3
string extension = PathUtils.GetExtension(path);
4
Console.WriteLine("File extension: " + extension);
Output:
xxxxxxxxxx
1
File extension: .txt
xxxxxxxxxx
1
public class PathUtils
2
{
3
private static Regex REGEX = new Regex(@"(\.[^.\/]+)$");
4
5
public static string GetExtension(string path)
6
{
7
Match match = REGEX.Match(path);
8
9
foreach(Group entry in match.Groups)
10
return entry.Value;
11
12
return "";
13
}
14
}
Example:
xxxxxxxxxx
1
string path = @"C:\path\to\file.txt";
2
3
string extension = PathUtils.GetExtension(path);
4
Console.WriteLine("File extension: " + extension);
Output:
xxxxxxxxxx
1
File extension: .txt