使用 Windows 相容性套件將程式碼移植到 .NET

將現有程式碼從 .NET Framework 移植到 .NET 時發現的一些最常見問題,是僅在 .NET Framework 中找到的 API 和技術相依性。 Windows 相容性套件提供許多這些技術,因此建置 .NET 應用程式和 .NET Standard 程式庫很容易。

相容性套件是 .NET Standard 2.0 的邏輯延伸模組,可大幅增加 API 集合。 現有的程式碼幾乎不會修改編譯。 為信守「所有 .NET 實作提供的 API 集」承諾,.NET Standard不包括無法跨所有平台的技術,例如登錄、Windows Management Instrumentation (WMI) 或反映發出 API。 Windows 相容性套件位階高於 .NET Standard,並提供存取僅限 Windows 的技術。 它特別適合想要移至 .NET,但至少第一個步驟計劃會停留在 Windows 的客戶。 在該案例中,您可以使用僅限 Windows 的技術來移除移轉障礙。

封裝內容

Windows 相容性套件透過 Microsoft.Windows.Compatibility NuGet 套件提供,可從以 .NET 或 .NET Standard 為目標的專案參考。

它提供約 20,000 個 API,包括僅限 Windows 以及來自下列技術領域的跨平台 API:

  • 字碼頁
  • CodeDom
  • 組態
  • 目錄服務
  • 繪圖
  • ODBC
  • 權限
  • 連接埠
  • Windows 存取控制清單 (ACL)
  • Windows Communication Foundation (WCF)
  • Windows 加密
  • Windows EventLog
  • Windows Management Instrumentation (WMI)
  • Windows 效能計數器
  • Windows 登錄
  • Windows 執行階段快取
  • Windows 服務

如需詳細資訊,請參閱相容性套件規格

開始使用

  1. 移植前,請務必查看移植程序

  2. 將現有的程式碼移植到 .NET 或 .NET Standard 時,請安裝 Microsoft.Windows.Compatibility NuGet 套件

    如果您想要留在 Windows,即已完成所有準備。

  3. 如果您想要在 Linux 或 macOS 上執行 .NET 應用程式或 .NET Standard 程式庫,請使用平台相容性分析器尋找無法跨平台運作的 API 使用方式。

  4. 移除這些 API 的使用方式,以跨平台的替代方案取代,或使用平台檢查保護它們,例如:

    private static string GetLoggingPath()
    {
        // Verify the code is running on Windows.
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Fabrikam\AssetManagement"))
            {
                if (key?.GetValue("LoggingDirectoryPath") is string configuredPath)
                    return configuredPath;
            }
        }
    
        // This is either not running on Windows or no logging path was configured,
        // so just use the path for non-roaming user-specific data files.
        var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        return Path.Combine(appDataPath, "Fabrikam", "AssetManagement", "Logging");
    }
    

如需示範,請查看 Channel 9 的 Windows 相容性套件影片