Posts tagged: DllImport(“Shell32.dll”)]

Get System default file icon using C#

By Ashish Khandelwal, February 23, 2010

Very easy way to get the associated icon for the given file:

Icon.ExtractAssociatedIcon Method

Syntax

public static Icon ExtractAssociatedIcon(
    string filePath
)

Detail

Returns an icon representation of an image contained in the specified file.

A relative path is assumed to be relative to the current working directory.

When ExtractAssociatedIcon is used with bitmaps, a thumbnail image may be returned instead of an icon if the system running the application has a registry setting that causes bitmap files to be shown as thumbnail images.

The following code example demonstrates how to use the ExtractAssociatedIcon method. To run this example, paste the code into a Windows Form and call ExtractAssociatedIconEx from the form’s constructor or Load event handler.

private void ExtractAssociatedIconEx()

{

    Icon ico =

        Icon.ExtractAssociatedIcon(@”C:\WINDOWS\system32\notepad.exe”);

    this.Icon = ico;

}

This is just one line of code to return the icon.

You will find verious articles on web to get the default icon, all these articles says to use unmanaged code and unsafe code ([DllImport("Shell32.dll")]), but when i tried to use this unmanged code, i found a problem that for some of the files it does not return the icon. I finally found ExtractAssociatedIcon() method and started using without any issue.

VN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)