TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Path.GetExtension: File Extension

This C# Path article shows how to use the Path.GetExtension method. It provides an alternative implementation.

Path.GetExtension. Most file names have a specific extension.

A program may only need to test for one file extension. We question if Path.GetExtension is ideal. We can use this method and also compare its performance to a simpler but custom method.

Info: You can use Path.GetExtension to test extensions. The method includes the separator character ".".

Example. We look at the functionality of the Path.GetExtension method. This method is found in the base class library. This code extracts the extension. The resulting extension includes the separator character, which is a dot.

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

Discussion. Here we look at some implementation issues. Most developers first turn to Path.GetExtension, but it can cause code to become more complicated. In the intermediate language, I found that Path.GetExtension does lots without telling us.

Path.GetExtension checks the entire path for invalid chars. This step is redundant if you already know your path is valid, such as when you received it from Directory.GetFiles. Also, it looks for a separator char.

Note: The implementation checks for DirectorySeparatorChar, AltDirectorySeparatorChar and VolumeSeparatorChar.

Changing extensions. This site also contains information about how you can change the extensions on path representations in memory. The .NET Framework provides the Path.ChangeExtension method for this purpose.

Path.ChangeExtension

Example 2. 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.

Tip: You can pull all the logic into a static helper method. This makes the code clearer and faster.

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

It tests the path for null. You cannot use an instance method, such as EndsWith, without an actual instance, so testing for null avoids exceptions here. It calls EndsWidth. 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.

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]

Summary. We looked at different ways you can check file extensions. The custom method here is more expressive to me. It also involves less file system code. It separates the implementation from the expression you want to test.

Note: There is some validity to always preferring the .NET Framework Path classes.

But: This alternative method here has merit with expressiveness and performance.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf