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.

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

Posted on 28/05/2014, in .NET, C#, WPF and tagged , , , . Bookmark the permalink. 1 Comment.

  1. Pretty! This hhas been an incredibly wonderful article.
    Thank you for providing these details.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s