views:

244

answers:

4

If I have the path to a file, is there a way I can get the icon that windows would have displayed for that file in Windows Explorer?

+1  A: 

http://www.codeguru.com/csharp/csharp/cs_misc/icons/article.php/c4261/ seems to have a decent example....

psychotik
+2  A: 

In C#, you will need to PInvoke the Win32 API call SHGetFileInfo(). There is a simple tutorial here that explains how: Getting Associated Icons Using C#.

Duncan Bayne
That's not necessarily true - if you're already referencing PresentationCore.dll you definitely don't want to do it this way.
280Z28
PresentationCore is WPF though, isn't it?
Svish
@Svish: It's only one of the WPF assemblies. You don't have to reference PresentationFramework to use this.
280Z28
+1  A: 

First of all, there are multiple sizes of images, some of which are easier to get than others. If you want the "normal" size one (I believe 32x32) and can use WPF (referencing PresentationCore), this is a great way to do it:

public System.Windows.Media.ImageSource Icon
{
    get
    {
        if (icon == null && System.IO.File.Exists(Command))
        {
            using (System.Drawing.Icon sysicon = System.Drawing.Icon.ExtractAssociatedIcon(Command))
            {
                // This new call in WPF finally allows us to read/display 32bit Windows file icons!
                icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                  sysicon.Handle,
                  System.Windows.Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            }
        }

        return icon;
    }
}
280Z28