How to extract default file icon in WPF application


documentIconsDemosl1

In Windows every file has default icon, and it is shown in Windows Explorer while browsing files on disk. If you want to grab this icon in WPF application there are several ways. One of the solution is by using ExtractAssociatedIcon from Icon class located in System.Drawing namespace.

The following code shows how to extract default icon from the file specified by file name:

var sysicon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
var bmpSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
            sysicon.Handle,
            System.Windows.Int32Rect.Empty,
            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
sysicon.Dispose();

Explanation of the code above is straightforward.First we need file path, then we need to call Icon.ExtractAssociatedIcon(filePath) to get Icon object. From the icon object we can create BitmapSource which can be show everywhere in the WPF application.

 

Complete source code demo can be found here.

Advertisement

2 thoughts on “How to extract default file icon in WPF application

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s