共用方式為


使用 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事件日誌
  • 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");
    }
    

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