Languages
[Edit]
EN

C# / .NET - get file extension

7 points
Created by:
Mohammad-Oneal
327

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# / .NET - file API

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join