Skip to content
Related Articles
Open in App
Not now

Related Articles

C# Program to Get Extension of a Given File

Improve Article
Save Article
  • Last Updated : 16 Feb, 2022
Improve Article
Save Article

DirectoryInfo class provides different types of methods and properties that are used to perform operations on directories and sub-directories like creating, moving, etc. This class has an Extension property which is used to find the extension part from the given file name which includes the dot format in the file’s full name. For example, if the file name is c:\gfg.txt, then this property will return “.txt”.

Syntax:

public string Extension { get; }

Return: It will return a string with an extension in the dot format of the current file. Even if it is the full file name or an empty string, or if no extension is available. 

Example:

C#




// C# program to find the extension of a given File
using System;
using System.IO;
 
class GFG{
 
static void Main()
{
 
    // Specify text file
    DirectoryInfo extension = new DirectoryInfo("my_data.txt");
 
    // Get the extension of the File
    // Using Extension property
    Console.WriteLine("File extension : " + extension.Extension);
 
    // Specify pdf file
    DirectoryInfo extension1 = new DirectoryInfo("my_data.pdf");
 
    // Get the extension of the File
    // Using Extension property
    Console.WriteLine("File extension : " + extension1.Extension);
 
    // Specify the file which has no extension
    DirectoryInfo extension2 = new DirectoryInfo("gfg");
 
    // Get the extension of the File
    // Using Extension property
    Console.WriteLine("File extension : " + extension2.Extension);
 
    // Specify the file which has multiple dots
    DirectoryInfo extension3 = new DirectoryInfo("gfg.gg.txt");
 
    // Get the extension of the File
    // Using Extension property
    Console.WriteLine("File extension : " + extension3.Extension);
}
}


Output:

File extension : .txt
File extension : .pdf
File extension : 
File extension : .txt
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!