C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: You can use Path.GetExtension to test extensions. The method includes the separator character "."
Note: This code isn't clear in several ways. First you have to know that the extension will have the dot at the start.
Also: You need to know whether the extension will be case sensitive—it is. The extension for "Test.txt" has four chars.
C# program that uses Path.GetExtension method
using System;
using System.IO;
class Program
{
static void Main()
{
string p = @"C:\Users\Sam\Documents\Test.txt";
string e = Path.GetExtension(p);
if (e == ".txt")
{
Console.WriteLine(e);
}
}
}
Output
.txt
Note: The implementation checks for DirectorySeparatorChar, AltDirectorySeparatorChar and VolumeSeparatorChar.
Tip: You can pull all the logic into a static helper method. This makes the code clearer and faster.
IsTxtFile: This tests the path for null. You cannot use an instance method without an actual instance, so testing for null avoids exceptions here.
EndsWith: IsTxtFile calls EndsWith to test the file extension. Your file extension is at the end of the path.
Opinion: What I like the most about this example is that it has a more natural-language, simpler interface.
C# program that uses custom path method
using System;
class Program
{
static void Main()
{
string p = @"C:\Users\Sam\Documents\Test.txt";
if (IsTxtFile(p))
{
Console.WriteLine(".txt");
}
}
static bool IsTxtFile(string f)
{
return f != null &&
f.EndsWith(".txt", StringComparison.Ordinal);
}
}
Output
.txt
File extension checking method benchmark:
Path.GetExtension: 1322 ms
Custom IsTxtFile method: 326 ms [faster]
Path.GetExtension: 1296 ms
Custom IsTxtFile method: 208 ms [faster]