How to: Extract the Icon Associated with a File in Windows Forms

Many files have embedded icons that provide a visual representation of the associated file type. For example, Microsoft Word documents contain an icon that identifies them as Word documents. When displaying files in a list control or table control, you may want to display the icon representing the file type next to each file name. You can do this easily by using the ExtractAssociatedIcon method.

The following code example demonstrates how to extract the icon associated with a file and display the file name and its associated icon in a ListView control.

Private listView1 As ListView
Private imageList1 As ImageList

Public Sub ExtractAssociatedIconEx()

    ' Initialize the ListView, ImageList and Form.
    listView1 = New ListView()
    imageList1 = New ImageList()
    listView1.Location = New Point(37, 12)
    listView1.Size = New Size(161, 242)
    listView1.SmallImageList = imageList1
    listView1.View = View.SmallIcon
    Me.ClientSize = New System.Drawing.Size(292, 266)
    Me.Text = "Form1" 

    ' Get the c:\ directory. 
    Dim dir As New System.IO.DirectoryInfo("c:\")

    Dim item As ListViewItem
    Dim file As System.IO.FileInfo
    For Each file In dir.GetFiles()

        ' Set a default icon for the file. 
        Dim iconForFile As Icon = SystemIcons.WinLogo

        item = New ListViewItem(file.Name, 1)

        ' Check to see if the image collection contains an image 
        ' for this extension, using the extension as a key. 
        If Not (imageList1.Images.ContainsKey(file.Extension)) Then 

            ' If not, add the image to the image list.
            iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName)
            imageList1.Images.Add(file.Extension, iconForFile)
        End If
        item.ImageKey = file.Extension

    Next file
End Sub

To compile the example:

  • Paste the preceding code into a Windows Form, and call the ExtractAssociatedIconExample method from the form's constructor or Load event-handling method.

    You will need to make sure that your form imports the System.IO namespace.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2014 Microsoft