C #: How can I get an icon for a specific file?

If I have a file path, is there a way to get the icon that windows will display for this file in Windows Explorer?

+3
source share
2 answers

First of all, there are several image sizes, some of which are easier to obtain than others. If you want the “regular” size one (I believe 32x32) and can use WPF (referring to PresentationCore), this is a great way to do this:

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;
    }
}
+6
source
System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
0
source

Source: https://habr.com/ru/post/1730511/


All Articles