Languages
[Edit]
EN

C# / .NET - get file extension

7 points
Created by:
JustMike
26120

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join