This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET 2.0+

Extracting the Icon for a File

In Microsoft Windows, all files have an associated icon that can help the user to quickly identify the file type. Icons may be embedded in an executable or dynamic linked library (DLL), or held in an icon file. In each case, it is easy to access the icon.

File Icons

Every file type recognised by Microsoft Windows has an icon associated with it that is displayed in various applications, including Windows Explorer. If a file is not of a known type, a default icon is shown instead. If you are writing software that works with files, you may want to display the file icons in a similar manner. This can be achieved using the Icon class.

The Icon class is found in the System.Drawing namespace. Instances of the class can be used to represent Windows icons and to obtain information relating to those icons or to convert them to other formats. The class also includes some static methods, one of which can be used to obtain an icon for a file. This method is named, "ExtractAssociatedIcon", and returns an Icon instance containing the image for a file. The path to the file is provided using the method's only parameter.

In this article we will create a simple Windows Forms project that allows the user to select a file. The icon for the file will then be displayed using the native format, and after converting the icon to a bitmap. You can download the source code using the link at the top of the article.

Creating the Sample Program

To create the program, start a new Windows Forms project. Add the following three controls and components to the default form by dragging them from the toolbox and arranging them as desired:

Control NameTypePurpose
IconAreaPictureBoxUsed to display the icon after conversion to a bitmap.
SelectFileButtonButtonWhen clicked, displays a dialog box to allow a file to be selected. Once selected, the icon is extracted from the file and displayed in the PictureBox.
FileSelectionDialogOpenFileDialogThe component that controls the display of the open file dialog box.

Extracting the Icon

The extraction of the icon will occur when the user clicks the button. This will display the open file dialog box to allow a file to be selected. When the OK button is clicked, the associated icon for the file's type will be obtained and used as the main form's icon, as shown in the title bar and taskbar. The icon will then be converted to a bitmap using the ToBitmap method and displayed in the PictureBox control.

To add the functionality, create a Click event for the button and add the following code:

if (FileSelectionDialog.ShowDialog() == DialogResult.OK)
    Icon icon = Icon.ExtractAssociatedIcon(FileSelectionDialog.FileName);
    this.Icon = icon;
    IconArea.Image = icon.ToBitmap();

You can now execute the program to see the icon extraction in operation.

26 June 2010