C#:如何获取某个文件的图标?

Svi*_*ish 3 c# windows icons file

如果我有一个文件的路径,有没有办法在Windows资源管理器中获取Windows将为该文件显示的图标?

Sam*_*ell 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `System.Windows.Interop.Imaging`类位于`PresentationCore.dll`中,它通常在WPF项目中引用. (2认同)