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.cs211 chars8 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