Monday, 23 November 2015

How to extract the associated icon of any file in C#.Net

To extract icon of any file, define the below class and the structure:

        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;

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 int DestroyIcon(IntPtr hIcon);

Now define the following function:

/* Define it globally so that you can use the same object for all  the files. */
public Bitmap extractAssociatedIcon(string fName)
            Icon myIcon = null;
                IntPtr hImgSmall;    //the handle to the system image list              

                hImgSmall = Win32.SHGetFileInfo(fName, 0, ref shinfo,
                                  Win32.SHGFI_ICON |

                if (shinfo.hIcon != IntPtr.Zero)
                    myIcon = Icon.FromHandle(shinfo.hIcon);              

            catch (Exception ex)
                // Handle any exception here
            return myIcon.ToBitmap();

Get the icon by calling the above defined function.

Bitmap image = extractAssociatedIcon("fullPath to the file");

Once you get the icon, make sure you destroy the icon. This is very important, else you will run into memory issues.


No comments:

Post a Comment