C# Program to Get Extension of a Given File
Last Updated :
16 Feb, 2022
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#
using System;
using System.IO;
class GFG{
static void Main()
{
DirectoryInfo extension = new DirectoryInfo( "my_data.txt" );
Console.WriteLine( "File extension : " + extension.Extension);
DirectoryInfo extension1 = new DirectoryInfo( "my_data.pdf" );
Console.WriteLine( "File extension : " + extension1.Extension);
DirectoryInfo extension2 = new DirectoryInfo( "gfg" );
Console.WriteLine( "File extension : " + extension2.Extension);
DirectoryInfo extension3 = new DirectoryInfo( "gfg.gg.txt" );
Console.WriteLine( "File extension : " + extension3.Extension);
}
}
|
Output:
File extension : .txt
File extension : .pdf
File extension :
File extension : .txt
Share your thoughts in the comments
Please Login to comment...