使用 Windows 兼容性包将代码移植到 .NET

将现有代码从 .NET Framework 移植到 .NET 时发现的一些最常见问题依赖于仅在 .NET Framework 中找到的 API 和技术。 Windows 兼容性包提供了许多这些技术,因此生成 .NET 应用程序和 .NET Standard 库要容易得多。

兼容性包是 .NET Standard 2.0 的逻辑扩展, 可显著增加 API 集。 现有代码几乎无需修改即可编译。 为了信守 .NET Standard 的承诺(“所有 .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 管理工具 (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 兼容性包的第 9 频道视频