Getting Associated Icons Using C#

Environment: VC#.NET

How to Use the SHGetFileInfo Function to Get the Icons That Are Associated with Files in Visual C# .NET

Summary

This step-by-step article describes how to use the SHGetFileInfo function to get the icons that are associated with files.

Create a Windows Forms Application

  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click Windows Application under Templates.
  4. In the Name box, type GetIconSample.

Use the SHGetFileInfo Function

  1. Add the following code in the Form1.cs file at the end of the USING statements:
  2. using System.Runtime.InteropServices;
  3. Add the following code at the beginning of the GetIconSample namespace:
  4. [StructLayout(LayoutKind.Sequential)]
    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
    
      [DllImport("shell32.dll")]
      public static extern IntPtr SHGetFileInfo(string pszPath,
                                  uint dwFileAttributes,
                                  ref SHFILEINFO psfi,
                                  uint cbSizeFileInfo,
                                  uint uFlags);
    }
    
  5. Add the following code in the Form1 class after the PRIVATE statements:
  6. private int nIndex = 0;
  7. Add a listView control, a button control, and an imageList control to the form. The default names are listView1, button1, and imageList1, respectively.
  8. In the Properties window of button1, set the button text to Select a File, and then add the following code in the button1_click event:
  9. IntPtr hImgSmall;    //the handle to the system image list
    IntPtr hImgLarge;    //the handle to the system image list
    string fName;        // 'the file name to get icon from
    SHFILEINFO shinfo = new SHFILEINFO();
    
    OpenFileDialog openFileDialog1   = new OpenFileDialog();
    openFileDialog1.InitialDirectory = "c:\\temp\\";
    openFileDialog1.Filter           = "All files (*.*)|*.*";
    openFileDialog1.FilterIndex      = 2;
    openFileDialog1.RestoreDirectory = true ;
    
    listView1.SmallImageList = imageList1;
    listView1.LargeImageList = imageList1;
    
    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
       fName = openFileDialog1.FileName;
       //Use this to get the small Icon
       hImgSmall = Win32.SHGetFileInfo(fName, 0, ref shinfo,
                                      (uint)Marshal.SizeOf(shinfo),
                                       Win32.SHGFI_ICON |
                                       Win32.SHGFI_SMALLICON);
    
      //Use this to get the large Icon
      //hImgLarge = SHGetFileInfo(fName, 0,
      //ref shinfo, (uint)Marshal.SizeOf(shinfo),
      //Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);
    
      //The icon is returned in the hIcon member of the shinfo
      //struct
      System.Drawing.Icon myIcon =
             System.Drawing.Icon.FromHandle(shinfo.hIcon);
    
      imageList1.Images.Add(myIcon);
    
      //Add file name and icon to listview
      listView1.Items.Add(fName, nIndex++);
    }
    

Run the Project

  1. Compile the project: On the Build menu, click Build Solution.
  2. Press F5 to run the project.
  3. Click Select a File, and then select a file in the Open dialog box. The name of the file and the icon that is associated with the file appear in the ListView control.


Comments

  • Respect!

    Posted by Mihail on 03/14/2014 04:39am

    Easy to understand, working good and fast. Excellent, thanks!

    Reply
  • it dosent work

    Posted by eran65 on 01/29/2011 08:03pm

    I HATE U MORE THEN LIFE ITSELF

    Reply
  • You MUSE use DestroyIcon() function after extracting an icon

    Posted by nigor on 04/14/2005 02:39pm

    You MUST use DestroyIcon function after extracting the icon, as per http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/functions/shgetfileinfo.asp
    
    Otherwise, you will encounter "OutOfMemory" exception if you add a large number of icons to the  ImageList, like 3000+
    
    The following function should be added to Win32 class:
    
    [DllImport("user32")]
    public static extern int DestroyIcon(IntPtr hIcon);
    
    And here is how to use it:
    
    //The icon is returned in the hIcon member of the shinfo struct
        System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon).Clone();
    
    // Destroy icon
    Win32.DestroyIcon(shinfo.hIcon);
    
    imageList1.Images.Add(myIcon);
    
    //Add file name and icon to listview
    listView1.Items.Add(fName, nIndex++);

    Reply
  • This seems copied from http://support.microsoft.com

    Posted by LRaiz on 03/24/2005 11:17am

    This article seems to be a cut and paste of http://support.microsoft.com/?kbid=319350

    Reply
  • IMPORTANT

    Posted by parvezhakim12 on 12/12/2004 12:19pm

    This also belongs to Microsoft MSDN magzine. The idea of showing it here is to free developers from searching up the MSDN, and many changes have been made to that article where ever possible. This article is belongs to Microsoft and i do not have any intention to get involved in some legal problems, misuse it or distribute it. Parvez Ahmad

    Reply
  • Get File Icon

    Posted by chandra.mohan on 10/05/2004 06:27am

    How to Use the SHGetFileInfo Function to Get the Icons That Are Associated with Files in Visual C# .NET Compact Framework ( in PocketPC, SmartPhone, and WinCE Devices )

    Reply
  • And what if ...

    Posted by Legacy on 11/04/2003 12:00am

    Originally posted by: Rob

    How to check if the image list already contains the image/icon associated with the file selected?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Managing your company's financials is the backbone of your business and is vital to the long-term health and viability of your company. To continue applying the necessary financial rigor to support rapid growth, the accounting department needs the right tools to most efficiently do their job. Read this white paper to understand the 10 essentials of a complete financial management system and how the right solution can help you keep up with the rapidly changing business world.

  • "Security" is the number one issue holding business leaders back from the cloud. But does the reality match the perception? Keeping data close to home, on premises, makes business and IT leaders feel inherently more secure. But the truth is, cloud solutions can offer companies real, tangible security advantages. Before you assume that on-site is the only way to keep data safe, it's worth taking a comprehensive approach to evaluating risks. Doing so can lead to big benefits.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds