ASP.NET, Coding

How to get details of a file extension including icon

The information about file extensions is stored the registry in HKEY_CLASSES_ROOTS. If the extension description exists, it will be under a sub-key of the same name. The “(Default)” value will contain the PROGID to lookup. When you look up the PROGID, in there – it will have the actual description.

If it does exist, like say “.zzz” – then Windows Explorer defaults to “ZZZ file” – so that’s what this method does too.

See the following C# code see this in action:

   private string GetFileTypeDescription(string fileName)
    {
        if (string.IsNullOrEmpty(fileName))
            throw new ArgumentException("Argument 'fileName' cannot be null or empty.");
 
        // Get the file extension in the form of ".doc" or ".xls"
        string extension = Path.GetExtension(fileName);
 
        // If there is no file extension, Windows Explorer just shows "File"
        if (string.IsNullOrEmpty(extension))
            return "File";
 
        // Get the upper case version, without the ".". So ".doc" turns into DOC. This is used for unknown file types. This is how
        // Windows Explorer shows unknown file types
        string extensionNoDot = extension.Substring(1, extension.Length - 1).ToUpper();
 
        // Go look up the extension in HKEY_CLASSES_ROOT
        RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension);
       
        // If this is null, the file extension isn't registered, so just return the extension in caps, without the . - and " file". So
        // somefile.pdb turns into "PDB file"
        if (extensionKey == null)
            return extensionNoDot + " file";
 
        // The root/default value for a registry sub-key should have the ProgId of the application that is used to open the file - so
        // go try to get that value.
        string lookupProgId = extensionKey.GetValue("", string.Empty).ToString();
 
        // If there is no default value, there is no application associated with the file extension.
        if (string.IsNullOrEmpty(extension))
            return extensionNoDot + " file"; ;
 
        // Go lookup the progid
        RegistryKey progIdKey = Registry.ClassesRoot.OpenSubKey(lookupProgId);
 
        // If the progid wasn't found, then show the default value.
        if (string.IsNullOrEmpty(extension))
            return extensionNoDot + " file"; ;
 
        // If we got here, the root/default value of the progid key should have the friendly name of the application, so return that.
        // But again, if there was an error or if it's empty, it defaults to the standard "EXT file" format.
        return progIdKey.GetValue("", extensionNoDot + " file").ToString();
 
    }

You Might Also Like