1

因为我能够将图像的正确文件类型作为 JPEG 图像。但我可以获取 pdf 文档或 sql 文件的文件类型。我正在使用以下代码:

public String Type
{
      get
      {
            return GetType(Path.GetExtension(_document.DocumentPath));
      }
 }
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 string GetType(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 "";
        }

正如我所看到的,regedit 中的 .pdf 文件中没有“OpenWithProgids”子项。那么如何获取这些文件类型。

例如在win 7在此处输入图像描述

与文件名和其他信息一起列出的文件类型,我希望在我的应用程序中使用相同的文件类型我可以 xps 文档但不能其他文档

4

1 回答 1

2

您可以使用 windows API SHGetFileInfo函数获取类型

        [Flags]
        private enum SHGFI : int
        {
            /// <summary>get type name</summary>
            TypeName = 0x000000400,
        }

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi,
            uint cbFileInfo, uint uFlags);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName;
        };

        private static void Main()
        {
            SHGFI flags = SHGFI.TypeName;
            SHFILEINFO shinfo = new SHFILEINFO();
           SHGetFileInfo(your path, 0,
                ref shinfo, (uint) Marshal.SizeOf(shinfo),(uint) flags);

            Console.WriteLine(shinfo.szTypeName);

            Console.ReadKey();
        }
于 2013-09-02T04:40:17.847 回答