System.Drawing.Common 替代方案(.NET 7 和非 Windows)
避免出现"System.Drawing.Common 在此平台上不受支持"的变通方法
- 在 Linux 和 macOS 平台上,.NET 6 和 .NET 7 无法实现System.Drawing.Common 。
- 您将收到一条异常消息,指示"此平台不支持 System.Drawing.Common"。
- 将 .NET 6 的System.Drawing.EnableUnixSupport运行时配置设置为true 。
- 请注意,.NET 7 也不再提供支持。
- 使用IronSoftware.Drawing开源库来替换 .NET 7 中的System.Drawing.Common 。
在 .NET 6 和 .NET 7 中,微软已停止在 Linux 和 macOS 上支持System.Drawing.Common 。 根据官方文档,该库仅适用于 Windows 平台。
- 在非 Windows 操作系统上,会抛出
TypeInitializationException异常,其内部异常为PlatformNotSupportedException。 - 在 .NET 6 中,当引用System.Drawing.Common 的代码被编译为非 Windows 操作系统时,平台分析器会发出编译时警告。 此外,除非设置了配置选项,否则将抛出以下运行时异常:
System.TypeInitializationException : The type initializer for 'Gdip' threw an exception. --- System.PlatformNotSupportedException : System.Drawing.Common is not supported on non-Windows platforms.
.NET 6 中的临时解决方法:
通过在 runtimeconfig.json 文件中将 System.Drawing.EnableUnixSupport 运行时配置开关设置为 true,以启用对非 Windows 平台的支持:
{
"runtimeOptions": {
"configProperties": {
"System.Drawing.EnableUnixSupport": true
}
}
}
在代码开头添加以下代码,即可通过编程方式启用 Unix 支持:
// Enables Unix support for System.Drawing in .NET 6. This setting is ignored in .NET 7.
System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);
// Enables Unix support for System.Drawing in .NET 6. This setting is ignored in .NET 7.
System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);
' Enables Unix support for System.Drawing in .NET 6. This setting is ignored in .NET 7.
System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", True)
.NET 7
.NET 7发布后,微软删除了该解决方案,完全取消了对Linux和macOS上System.Drawing.Common的支持。
Iron Software 发布了System.Drawing.Common的开源替代品,名为IronSoftware.Drawing 。 您可以在NuGet和GitHub上找到它。
欲了解更多信息,您可以访问文档页面:Iron Software Drawing Documentation

