Win10下WPF使用System.Drawing.Common遇平台不支持错误求助
解决WPF .NET Core3.1提取EXE图标报错问题
问题根源
你安装的System.Drawing.Common 7.0.0是针对.NET 6+版本的,和你的.NET Core3.1项目版本不兼容,导致平台支持异常。另外你添加的System.Drawing.EnableUnixSupport配置是给Unix平台用的,Windows环境下完全无效。
解决方案
方案1:降级System.Drawing.Common版本(最简单)
卸载当前7.0.0版本,安装适配.NET Core3.1的4.7.2版本:
- 打开VS的「项目→管理NuGet程序包」
- 在「已安装」标签找到System.Drawing.Common,点击卸载
- 切换到「浏览」标签,搜索System.Drawing.Common,选择4.7.2版本安装
- 安装完成后重新运行项目,
Icon.ExtractAssociatedIcon(filePath)就能正常工作
方案2:用Windows原生API提取图标(更适配WPF)
如果不想依赖System.Drawing,直接调用Windows Shell API提取图标,转换为WPF原生的ImageSource,完全避免平台兼容问题:
- 先添加API调用的结构体和方法定义:
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Drawing; [StructLayout(LayoutKind.Sequential)] private struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; } [DllImport("shell32.dll")] private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); [DllImport("user32.dll")] private static extern bool DestroyIcon(IntPtr hIcon); private const uint SHGFI_ICON = 0x100; private const uint SHGFI_LARGEICON = 0x0; // 提取大图标(32x32) private const uint SHGFI_SMALLICON = 0x1; // 提取小图标(16x16)
- 编写提取图标的方法:
public ImageSource GetExeIcon(string filePath, bool useLargeIcon = true) { SHFILEINFO fileInfo = new SHFILEINFO(); uint flags = SHGFI_ICON | (useLargeIcon ? SHGFI_LARGEICON : SHGFI_SMALLICON); // 调用API获取图标句柄 SHGetFileInfo(filePath, 0, ref fileInfo, (uint)Marshal.SizeOf(fileInfo), flags); if (fileInfo.hIcon == IntPtr.Zero) return null; // 转换为WPF可用的ImageSource using (Icon icon = Icon.FromHandle(fileInfo.hIcon)) { ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon( icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); imageSource.Freeze(); // 冻结对象提升性能 DestroyIcon(fileInfo.hIcon); // 释放系统资源 return imageSource; } }
- 调用示例:
// 假设你已经获取到选中的exe路径filePath ImageSource exeIcon = GetExeIcon(filePath); // 直接绑定到WPF的Image控件或者按钮图标 yourButtonIcon.Source = exeIcon;
额外说明
.NET Core3.1环境下,System.Drawing.Common的4.x版本仅支持Windows平台,完全满足你的需求;如果后续升级到.NET 6+,则需要在项目文件(.csproj)中添加配置启用Windows支持:
<PropertyGroup> <RuntimeIdentifier>win-x64</RuntimeIdentifier> </PropertyGroup> <ItemGroup> <RuntimeHostConfigurationOption Include="System.Drawing.EnableWindowsSupport" Value="true" /> </ItemGroup>
内容的提问来源于stack exchange,提问作者patrick
相关产品推荐
相关产品推荐

