How can I get the description of a file extension in .NET

前端 未结 5 2037
囚心锁ツ
囚心锁ツ 2020-12-11 05:52

HI,

Windows provides descriptions for file extension such as \"Control Panel Item\" for .cpl files and \"PowerISO File\" for .daa files. Is there any way I can obtai

5条回答
  •  半阙折子戏
    2020-12-11 06:28

    You can search the registry like this:

    • Search default value of the extension in HKEY_CLASSES_ROOT. For example The default value of HKEY_CLASSES_ROOT\.txt is txtfile.
    • Then search default value of the previous result: For example The default value of HKEY_CLASSES_ROOT\txtfile is Text Document.

    After two searches the answer is Text Document.

    You can test any other extension by RegEdit.

    Visit this link: http://www.codeproject.com/KB/cs/GetFileTypeAndIcon.aspx?display=Print

    This is implementation of these two searches:

    public static class Helper
    {
        public static string GetFileDescription(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
    
            RegistryKey registryKey1 = null;
            RegistryKey registryKey2 = null;
            try
            {
                FileInfo fileInfo = new FileInfo(fileName);
    
                if (string.IsNullOrEmpty(fileInfo.Extension))
                {
                    return string.Empty;
                }
    
                string extension = fileInfo.Extension.ToLowerInvariant();
    
                registryKey1 = Registry.ClassesRoot.OpenSubKey(extension);
                if (registryKey1 == null)
                {
                    return string.Empty;
                }
    
                object extensionDefaultObject = registryKey1.GetValue(null);
                if (!(extensionDefaultObject is string))
                {
                    return string.Empty;
                }
    
                string extensionDefaultValue = (string)extensionDefaultObject;
    
                registryKey2 = Registry.ClassesRoot.OpenSubKey(extensionDefaultValue);
                if (registryKey2 == null)
                {
                    return string.Empty;
                }
    
                object fileDescriptionObject = registryKey2.GetValue(null);
                if (!(fileDescriptionObject is string))
                {
                    return string.Empty;
                }
    
                string fileDescription = (string)fileDescriptionObject;
                return fileDescription;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                if (registryKey2 != null)
                {
                    registryKey2.Close();
                }
    
                if (registryKey1 != null)
                {
                    registryKey1.Close();
                }
            }
        }
    }
    

提交回复
热议问题