Languages
[Edit]
EN

C# / .NET - get file extension

7 points
Created by:
JustMike
3506

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

References

  1. Path.GetExtension Method - Microsoft Docs
  2. String.LastIndexOf Method - Microsoft Docs
  3. Regex.Match Method - Microsoft Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.