System.Drawing.Common 替代方案 (.NET 7 與非 Windows)
避免"System.Drawing.Common 不支援此平台"的變通方法
- 在 .NET 6 和 .NET 7 的 Linux 和 macOS 平台上無法實現 System.Drawing.Common。
- 您將收到一個例外訊息,表明"System.Drawing.Common 不支援此平台"。
- 將 System.Drawing.EnableUnixSupport 執行時配置設定為 true,以支援 .NET 6。
- 請注意,.NET 7 中不再提供此支援。
- 使用 IronSoftware.Drawing 開源程式庫來取代 .NET 7 的 System.Drawing.Common。
在 .NET 6 和 .NET 7 中,Microsoft 已停止在 Linux 和 macOS 上支援 System.Drawing.Common。 該程式庫將僅在 Windows 平台上運行,根據官方文件。
- 在非 Windows 作業系統上,會丟擲一個
TypeInitializationException並以PlatformNotSupportedException作為內部例外。 - 在 .NET 6 中,當為非 Windows 作業系統編譯引用 System.Drawing.Common 的程式碼時,平台分析器會發出編譯時警告。 此外,除非設置一個配置選項,否則會丟擲以下執行時例外:
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 的發佈,Microsoft 已經移除了變通方法,完全移除在 Linux 和 macOS 上對 System.Drawing.Common 的支援。
Iron Software 發布了一個開源的替代方案,取代 System.Drawing.Common,稱為 IronSoftware.Drawing。 You can find it on NuGet and GitHub.
如需了解更多資訊,您可以造訪文件頁面:Iron Software Drawing Documentation

