/// <summary> /// 通过文件类型获取图标 /// </summary> /// <param name="fileType"></param> /// <param name="isLarge"></param> /// <returns></returns> public static System.Drawing.Icon GetIconByFileType(string fileType, bool isLarge) { if (fileType == null || fileType.Equals(string.Empty)) { return(null); } RegistryKey regVersion = null; string regFileType = null; string regIconString = null; string systemDirectory = Environment.SystemDirectory; if (fileType[0] == '.') { //读系统注册表中文件类型信息 regVersion = Registry.ClassesRoot.OpenSubKey(fileType, true); if (regVersion != null) { regFileType = regVersion.GetValue("") as string; regVersion.Close(); regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon", true); if (regVersion != null) { regIconString = regVersion.GetValue("") as string; regVersion.Close(); } } if (regIconString == null) { //没有读取到文件类型注册信息,指定为未知文件类型的图标 regIconString = System.IO.Path.Combine(systemDirectory, "shell32.dll,0"); } } else { //直接指定为文件夹图标 regIconString = System.IO.Path.Combine(systemDirectory, "shell32.dll,3"); } string[] fileIcon = regIconString.Split(new char[] { ',' }); if (fileIcon.Length != 2) { //系统注册表中注册的标图不能直接提取,则返回可执行文件的通用图标 fileIcon = new string[] { System.IO.Path.Combine(systemDirectory, "shell32.dll"), "2" }; } System.Drawing.Icon resultIcon = null; try { //调用API方法读取图标 int[] phiconLarge = new int[1]; int[] phiconSmall = new int[1]; uint count = FileApi.ExtractIconEx(fileIcon[0], Int32.Parse(fileIcon[1]), phiconLarge, phiconSmall, 1); IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]); resultIcon = System.Drawing.Icon.FromHandle(IconHnd); } catch { } return(resultIcon); }
/// <summary> /// 通过文件名获取图标 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static System.Drawing.Icon GetIconByFileName(string fileName) { if (fileName == null || fileName.Equals(string.Empty)) { return(null); } if (!System.IO.File.Exists(fileName)) { return(null); } FileApi.SHFILEINFO shinfo = new FileApi.SHFILEINFO(); FileApi.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), FileApi.SHGFI_ICON | FileApi.SHGFI_SMALLICON); System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon); return(myIcon); }