Get File Extension in C#

Introduction

The Extension property of the FileInfo class returns the extension of a file. The following code snippet returns the extension of a file.

C# Get File Extension

string extn = fi.Extension;
Console.WriteLine("File Extension: {0}", extn);

Example

Here is a complete code example. Don't forget to import System.IO and System.Text namespaces in your project. The following code example uses a FileInfo class to create an object by passing a complete filename. The FileInfo class provides properties to get information about a file, such as file name, size, full path, extension, and directory name, and is read-only when the file was created and last updated.

// Full file name. Change your file name
string fileName = @"/Users/praveen/Desktop/images/November.pdf";
FileInfo fi = new FileInfo(fileName);

// Get File Name
string justFileName = fi.Name;
Console.WriteLine("File Name: {0}", justFileName);

// Get file name with full path
string fullFileName = fi.FullName;
Console.WriteLine("File Name: {0}", fullFileName);

// Get file extension
string extn = fi.Extension;
Console.WriteLine("File Extension: {0}", extn);

// Get directory name
string directoryName = fi.DirectoryName;
Console.WriteLine("Directory Name: {0}", directoryName);

// File Exists ?
bool exists = fi.Exists;
Console.WriteLine("File Exists: {0}", exists);

if (fi.Exists)
{
    // Get file size
    long size = fi.Length;
    Console.WriteLine("File Size in Bytes: {0}", size);

    // File ReadOnly ?
    bool IsReadOnly = fi.IsReadOnly;
    Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);

    // Creation, last access, and last write time
    DateTime creationTime = fi.CreationTime;
    Console.WriteLine("Creation time: {0}", creationTime);

    DateTime accessTime = fi.LastAccessTime;
    Console.WriteLine("Last access time: {0}", accessTime);

    DateTime updatedTime = fi.LastWriteTime;
    Console.WriteLine("Last write time: {0}", updatedTime);
}

The output looks like the following, where you can see the file extension is displayed.

Output Window

Here is a free ebook download on FileInfo. FileInfo in C#


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.