【问题标题】:C#: How can I get the icon for a certain file?C#:如何获取某个文件的图标?
【发布时间】:2010-01-29 09:17:25
【问题描述】:

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

【问题讨论】:

    标签: c# windows file icons


    【解决方案1】:

    首先,图片有多种尺寸,其中一些比其他更容易获得。如果您想要“正常”尺寸(我相信 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 有什么关系?您使用与 WPF 无关的 Interop!
    • System.Windows.Interop.Imaging 类位于PresentationCore.dll,通常在 WPF 项目中引用。
    【解决方案2】:
    System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多