Path.GetExtension
Most file names have a specific extension. You can use Path.GetExtension
in C# to test extensions. The method includes the separator character "."
We can use this method and also compare its performance to a simpler but custom method. Path
methods can cause unneeded processing in some programs.
We look at the functionality of the Path.GetExtension
method. This code extracts the extension. The resulting extension includes the separator character, which is a dot.
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); } } }.txt
Here we see an alternative method to check the file extensions. Often you can rewrite the framework methods so that your code does far less internally, and is also clearer to read.
static
helper method. This makes the code clearer and faster.null
. You cannot use an instance method without an instance, so testing for null
avoids exceptions here.IsTxtFile
calls EndsWith
to test the file extension. Your file extension is at the end of the path.interface
.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); } }.txtPath.GetExtension: 1322 ms Custom IsTxtFile method: 326 ms [faster] Path.GetExtension: 1296 ms Custom IsTxtFile method: 208 ms [faster]
Most developers first turn to Path.GetExtension
, but it can cause code to become more complicated. Path.GetExtension
has several logic checks.
Path.GetExtension
checks the entire path for invalid chars. This step is redundant if you already know your path is valid.char
. The implementation checks for DirectorySeparatorChar
, AltDirectorySeparatorChar
and VolumeSeparatorChar
.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.