C#: 如何获取特定文件的图标?

3

如果我有一个文件的路径,是否有办法获取Windows Explorer中显示该文件所用的图标?

2个回答

6

首先,图像有多种尺寸,其中一些比其他尺寸更容易获取。如果您想要“正常”大小的图像(我相信是32x32),并且可以使用WPF(引用PresentationCore),那么这是一个很好的方法:

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

你的代码与WPF有什么关系?你使用的Interop与WPF无关! - msfanboy
2
System.Windows.Interop.Imaging 类位于 PresentationCore.dll 中,通常在 WPF 项目中引用。 - Jake Berger

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接