How do you get a file extension in C#?

← .NET and C# answers

Path.GetExtension("folder/report.pdf") returns ".pdf" including the dot, and an empty string when there is no extension.

using System.IO;
 
string path = @"C:\data\Report.Final.PDF";
 
Path.GetExtension(path);                    // ".PDF"
Path.GetFileName(path);                     // "Report.Final.PDF"
Path.GetFileNameWithoutExtension(path);     // "Report.Final"
Path.ChangeExtension(path, ".txt");         // C:\data\Report.Final.txt
 
bool isPdf = string.Equals(
    Path.GetExtension(path), ".pdf", StringComparison.OrdinalIgnoreCase);

Only the part after the last dot counts, and file names such as .gitignore or archive.tar.gz give .gitignore and .gz. Compare extensions without regard to case, and do not trust an extension to prove what a file contains.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required