Search code examples
c#fileproperties

How to get the file type name?


I want to get in my c# app the name of the file type, that is shown in file properties in windows... for example .log file has the type as LOG file (.log) or .bat has Batch file for Windows (.bat)(translated from my lang, so maybe not accurate).

Please, where can i find this info? or how to get to this? i found Get-Registered-File-Types-and-Their-Associated-Ico article, where the autor shows how to get the icon, but not the type name of file that is showed in OS.


Solution

  • You can read that info from the registry

    use like GetDescription("cpp") or GetDescription(".xml")

    public static string ReadDefaultValue(string regKey)
    {
        using (var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(regKey, false))
        {
            if (key != null)
            {
                return key.GetValue("") as string;
            }
        }
        return null;
    }
    
    public static string GetDescription(string ext)
    {
        if (ext.StartsWith(".") && ext.Length > 1) ext = ext.Substring(1);
    
        var retVal = ReadDefaultValue(ext + "file");
        if (!String.IsNullOrEmpty(retVal)) return retVal;
    
    
        using (var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("." + ext, false))
        {
            if (key == null) return "";
    
            using (var subkey = key.OpenSubKey("OpenWithProgids"))
            {
                if (subkey == null) return "";
    
                var names = subkey.GetValueNames();
                if (names == null || names.Length == 0) return "";
    
                foreach (var name in names)
                {
                    retVal = ReadDefaultValue(name);
                    if (!String.IsNullOrEmpty(retVal)) return retVal;
                }
            }
        }
    
        return "";
    }