How to get file extension in C#

It looks like this is a fairly popular interview question, particularly in junior or entry level .Net developer positions.

While there are tons way to do this, I am listing two common approaches.

  • The most common way is string manipulation:
    string file = "abc.xml";
    Console.WriteLine(file.Substring(file.LastIndexOf(".") + 1));
    
    /// Returns xml
    
  • .Net also has native class Path allows you to get file extension:
    /// Because Path.GetExtension returns extension ends with a dot, so you may want to get rid of it. 
    string file = "abc.xml";
    Path.GetExtension(file).Replace(".", "")
    /// Returns xml
    

Path also has a list of other handy file IO methods:

  • ChangeExtension(string path, string extension)
  • GetPathRoot(string path);
  • GetDirectoryName(string path);
  • GetExtension(string path);
  • GetFileName(string path);
  • GetFileNameWithoutExtension(string path);
  • GetFullPath(string path);
  • GetInvalidFileNameChars();
  • GetInvalidPathChars();
  • GetPathRoot(string path);
  • GetRandomFileName();
  • GetTempFileName();
  • GetTempPath();
  • HasExtension(string path);
  • IsPathRooted(string path);

More details are available at http://msdn.microsoft.com/en-us/library/system.io.path.aspx

^ Top of Page