Detail This tests the path for null. You cannot use an instance method without an instance, so testing for null avoids exceptions here.
Detail IsTxtFile calls EndsWith to test the file extension. Your file extension is at the end of the path.
Detail What I like the most about this example is that it has a more natural-language, simpler interface.
static void Main()
string p = @"C:\Users\Sam\Documents\Test.txt";
static bool IsTxtFile(string f)
return f != null &&
}.txtPath.GetExtension: 1322 ms
Custom IsTxtFile method: 326 ms [faster]
Path.GetExtension: 1296 ms
Custom IsTxtFile method: 208 ms [faster]
Discussion. Most developers first turn to Path.GetExtension, but it can cause code to become more complicated. Path.GetExtension has several logic checks.
Info Path.GetExtension checks the entire path for invalid chars. This step is redundant if you already know your path is valid.
Also It looks for a separator char. The implementation checks for DirectorySeparatorChar, AltDirectorySeparatorChar and VolumeSeparatorChar.
A summary. We looked at ways you can check file extensions. The custom method here involves less file system code. It separates the implementation from the expression you want to test.