How to Get a File Extension in C#

C# get file extension. FileInfo.Extension property returns the file extension in C#.

C# Get File Extension

 
The Extension property of the FileInfo class returns the extension of a file. The following code snippet returns the extension of a file.
  1. string extn = fi.Extension;  
  2. Console.WriteLine("File Extension: {0}", extn);  

C# File Extension Code 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, directory name, is read only, when the file was created and last updated. 
  1. // Full file name. Change your file name   
  2. string fileName = @"/Users/praveen/Desktop/images/November.pdf";  
  3. FileInfo fi = new FileInfo(fileName);  
  4.   
  5. // Get File Name  
  6. string justFileName = fi.Name;  
  7. Console.WriteLine("File Name: {0}", justFileName);  
  8. // Get file name with full path   
  9. string fullFileName = fi.FullName;  
  10. Console.WriteLine("File Name: {0}", fullFileName);  
  11. // Get file extension   
  12. string extn = fi.Extension;  
  13. Console.WriteLine("File Extension: {0}", extn);  
  14. // Get directory name   
  15. string directoryName = fi.DirectoryName;  
  16. Console.WriteLine("Directory Name: {0}", directoryName);  
  17. // File Exists ?  
  18. bool exists = fi.Exists;  
  19. Console.WriteLine("File Exists: {0}", exists);  
  20. if (fi.Exists)  
  21. {  
  22.     // Get file size  
  23.     long size = fi.Length;  
  24.     Console.WriteLine("File Size in Bytes: {0}", size);  
  25.     // File ReadOnly ?  
  26.     bool IsReadOnly = fi.IsReadOnly;  
  27.     Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);  
  28.     // Creation, last access, and last write time   
  29.     DateTime creationTime = fi.CreationTime;  
  30.     Console.WriteLine("Creation time: {0}", creationTime);  
  31.     DateTime accessTime = fi.LastAccessTime;  
  32.     Console.WriteLine("Last access time: {0}", accessTime);  
  33.     DateTime updatedTime = fi.LastWriteTime;  
  34.     Console.WriteLine("Last write time: {0}", updatedTime);  
  35. }  
The output looks like the following where you can see the file extension is displayed.
 
 
 
Here is a free ebook download on FileInfo. FileInfo in C#