You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行蓝牙LE扫描代码时遇System.Private.CoreLib加载失败求助

解决BLE扫描代码加载System.Private.CoreLib失败问题

问题根源

错误源于UWP版本的System.Runtime.WindowsRuntime.dll与当前.NET运行时(.NET Core/.NET 5+)存在兼容性冲突,该UWP组件依赖的System.Private.CoreLib版本(4.0.0.0)和当前运行环境版本不匹配,导致加载失败。

具体修复步骤

1. 移除UWP NuGet包引用

  • 在NuGet包管理器中卸载所有UWP相关的System.Runtime.WindowsRuntime类包(如Microsoft.Windows.SDK.Contracts或独立的System.Runtime.WindowsRuntime)。
  • 打开项目文件(.csproj),删除所有残留的UWP相关引用节点,例如:
    <PackageReference Include="Microsoft.Windows.SDK.Contracts" Version="xxx" />
    

2. 添加适配的Windows Runtime引用

对于.NET Core/.NET 5+项目,无需手动引用System.Runtime.WindowsRuntime.dll,通过配置项目文件自动引入正确依赖:

  • 在.csproj中添加以下配置,指定带Windows版本的目标框架:
    <PropertyGroup>
      <TargetFramework>net6.0-windows10.0.19041.0</TargetFramework> <!-- 替换为你的Windows SDK版本 -->
      <UseWindowsForms>true</UseWindowsForms> <!-- WinForms项目用此配置,WPF项目改为UseWPF=true -->
      <PlatformTarget>x64</PlatformTarget> <!-- BLE API仅支持x64/x86,禁用AnyCPU -->
    </PropertyGroup>
    

3. 适配当前.NET版本的BLE扫描代码

以下是标准的DeviceWatcher扫描BLE设备示例(适配.NET 6+ Windows平台):

using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Enumeration;

public class BleScanner
{
    private BluetoothLEAdvertisementWatcher _watcher;

    public void StartScanning()
    {
        _watcher = new BluetoothLEAdvertisementWatcher();
        _watcher.Received += OnAdvertisementReceived;
        _watcher.Start();
    }

    private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
    {
        Console.WriteLine($"设备名称: {args.Advertisement.LocalName}, 信号强度: {args.RawSignalStrengthInDBm}");
    }

    public void StopScanning()
    {
        _watcher?.Stop();
        _watcher?.Received -= OnAdvertisementReceived;
        _watcher = null;
    }
}

4. 验证运行环境与项目配置

  • 确保Windows系统版本不低于Windows 10 1903(10.0.18362),BLE相关API在此版本后才稳定支持。
  • 项目属性中目标平台设置为x64或x86,不要使用AnyCPU模式。

5. 清理重建项目

  • 执行Clean Solution后再Rebuild Solution,清除旧编译缓存。
  • 手动删除项目目录下的bin和obj文件夹,重新编译项目。

额外注意事项

  • 禁止手动复制或引用UWP路径下的System.Runtime.WindowsRuntime.dll,.NET Core/.NET 5+会自动从Windows SDK加载正确版本。
  • 若项目基于.NET Framework(如4.5+),需引用.NET Framework版本的System.Runtime.WindowsRuntime,路径为C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.WindowsRuntime.dll。

内容的提问来源于stack exchange,提问作者bob0815

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:55:20