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?
Asked
Active
Viewed 6,287 times
2 Answers
6
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;
}
}

Sam Harwell
- 97,721
- 20
- 209
- 280
-
What has your code to do with WPF ? You use Interop which has nothing to do with WPF! – msfanboy Mar 11 '11 at 22:08
-
2`System.Windows.Interop.Imaging` class is located in `PresentationCore.dll`, which is normally referenced in WPF projects. – Jake Berger May 01 '12 at 16:53
0
System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);

Keith Maurino
- 3,374
- 10
- 40
- 48