find the extension of a file in csharp

One way to find the extension of a file in C# is to use the Path class from the System.IO namespace. Specifically, we can use the Path.GetExtension method to get the file extension.

Here is an example code block that demonstrates this:

main.cs
using System.IO;

string path = "C:/path/to/myfile.txt";
string extension = Path.GetExtension(path); // returns ".txt"

// you can remove the dot if needed
extension = extension.TrimStart('.'); // returns "txt"
211 chars
8 lines

In this example, we are first creating a string variable path to hold the path to our file. Then, we are calling Path.GetExtension(path) to get the extension of the file, which will return a string containing the extension (including the leading "."). Finally, we are stripping the leading "." from the extension by calling TrimStart('.').

Note that if the specified file does not have an extension, this method will return an empty string.

gistlibby LogSnag