C # to read "Registered File Types" icon and the reading method of the specified file icon

using System;
using System.IO;
using System.Drawing;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace GetIconDemo
    /// <summary>
    ///  Provides a read from the operating system icons
    /// </summary>
    public class GetSystemIcon
        /// <summary>
        ///  Pursuant to the filename to read icon, if the specified file does not exist  , NULL is returned  .
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static Icon GetIconByFileName(string fileName)
            if (fileName == null || fileName.Equals(string.Empty)) return null;
            if (!File.Exists(fileName)) return null;

            SHFILEINFO shinfo = new SHFILEINFO();
            //Use this to get the small Icon
            Win32.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
            //The icon is returned in the hIcon member of the shinfo struct
            System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
            return myIcon;

        /// <summary>
        ///  Give the file name extension  (.*), Returns the corresponding icon
        ///  If not to the "." Returns the beginning of the folder icon  .
        /// </summary>
        /// <param name="fileType"></param>
        /// <param name="isLarge"></param>
        /// <returns></returns>
        public static 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] == '.')
                // Read the system registry file type information
                regVersion = Registry.ClassesRoot.OpenSubKey(fileType, true);
                if (regVersion != null)
                    regFileType = regVersion.GetValue("") as string;
                    regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon", true);
                    if (regVersion != null)
                        regIconString = regVersion.GetValue("") as string;
                if (regIconString == null)
                    // No read to a file type registration information, specified as an unknown file type icons
                    regIconString = systemDirectory + "shell32.dll,0";
                // Directly specified as the folder icon
                regIconString = systemDirectory + "shell32.dll,3";
            string[] fileIcon = regIconString.Split(new char[] { ',' });
            if (fileIcon.Length != 2)
                // System registry of plotting cannot directly extract, it returns the executable's universal icon
                fileIcon = new string[] { systemDirectory + "shell32.dll", "2" };
            Icon resultIcon = null;
                // Call the API method to read icon
                int[] phiconLarge = new int[1];
                int[] phiconSmall = new int[1];
                uint count = Win32.ExtractIconEx(fileIcon[0], Int32.Parse(fileIcon[1]), phiconLarge, phiconSmall, 1);
                IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);
                resultIcon = Icon.FromHandle(IconHnd);
            catch { }
            return resultIcon;

    public struct SHFILEINFO
        public IntPtr hIcon;
        public IntPtr iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;

    /// <summary>
    ///  Definition of API method called
    /// </summary>
    class Win32
        public const uint SHGFI_ICON = 0x100;
        public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
        public const uint SHGFI_SMALLICON = 0x1; // 'Small icon

        public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
        public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);


 This article from CSDN blog  , Reprinted, with the citation  :http://blog.csdn.net/snlei/archive/2009/03/08/3970345.aspx
分类:DotNet 时间:2010-04-12 人气:276
blog comments powered by Disqus


  • Install "Microsoft Pocket PC 2003 SDK.msi" or "Microsoft SMARTPHONE 2003 SDK.msi" encountered "wsc 2010-08-27

    In the installed evc (Embedded Visual C + +, embedded development software), press the order of installation: -> MicrosoftActiveSync_setup_cn-4.1.exe -> EVC4.exe -> Evc4sp4.exe -> Microsoft Pocket PC 2003 SDK.msi -> Microsoft SMARTPHONE 200

  • Microsoft internal patch (unofficial) of the method for obtaining (20,110,713) 2011-08-06

    http://support.microsoft.com/?kbid = kb behind the digital input can get this patch in ms and immediately requested information within the patch download. Examples are as follows: http://support.microsoft.com/?kbid=954232 * Press the upper left corne

  • java Applications Gallery 3: Regular Expressions operated jxl excel 2010-07-13

    Project development in the recent operation of the excel more frequent and regular expressions were combined with some processing, tidy. 1. Regular expressions commonly used method /** * In the first search string matches the number of strings * @par

  • String.Format method to format the format item syntax and examples 2010-11-18

    Name Help String.Format (String, Object) String in the specified format item is replaced the value of the specified Object instances the text equivalent. By the. NET Compact Framework support. String.Format (String, Object []) The format of the speci

  • WPF 基础到企业应用系列5--WPF千年轮回 续前缘 2012-03-09

    一,摘要 首先很高兴这个系列能得到大家的关注和支持,前端时间身体状况不适,所以暂停了更新,对此表示非常抱歉,以后会逐渐加快进度,不过由于这是一个很长的系列,我也想把它写好,所以以后也会慢慢来,在这个系列的过程中也会穿插发一些其他文章,比如Windows Azure.设计模式.WCF.Silverlight等,同时也会发一些自己的技术随感和心得,反正只要自己写得开心且对大家有帮助就行.由于自己才疏学浅且是对这些技术的使用总结和心得体会,错误之处在所难免,怀着技术交流的心态,在这里发表出来,所以希望

  • [EhCache]Java缓存框架使用EhCache结合Spring AOP 2012-08-07

    一.Ehcache简介 EhCache是一个纯Java的进程内缓存框架,具有如下特点: 1. 快速简单,非常容易和应用集成. 2.支持多种缓存策略 . 3. 缓存数据有两级:内存和磁盘,因此无需担心容量问题 . 4. 缓存数据会在虚拟机重启的过程中写入磁盘 . 5. 可以通过RMI.可插入API等方式进行分布式缓存. 6. 具有缓存和缓存管理器的侦听接口 . 7. 支持多缓存管理器实例,以及一个实例的多个缓存区域 等特点. 二.Ehcache配置的相关参数 Ehcache的配置很灵活,官方提供的

  • Flex and AS3 Common Knowledge of 100 2008-10-05

    【Change the output swf scale, background color, or frame rate】 In the "Navigator" window frame right inside your project "select" Properties "> select" ActionScript Compiler "> in the" Additional compiler argu

  • flex 100 small knowledge 2010-02-27

    http://www.javaeye.com/topic/311216 [ Change the scale of the output swf , Background color or frame rate ] In the "Navigator" window frames in your project right > Selected "Properties"> Selected "ActionScript Compiler"

  • Dive Into Python cn notes 2010-03-11

    Dive Into Python cn notes =========================== 2010,01,18 Dive Into Python version: 5.4b version of the woodpecker community translation 1. Tuple is no way. Can not change, suitable constants. Available to only traverse the list to use when hi

  • Passed on with jquery json object to the struts2 way of the complex 2010-07-09

    Error message: There java.lang.NoSuchMethodException setUser ([LJava.lang.String;) Exception struts2 in UserAction: 1 public class UserAction ( 2 private User user; 3 private String name; 4 public void setName (String name) ( 5 this.name = name; 6) 7

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.169 (s). 12 q(s)