开发者

C#: How can I get the icon for a certain file?

If I开发者_C百科 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?


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;
    }
}


System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜