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

System.Device.Location.Portable兼容问题与GeoCoordinateWatcher报错解决咨询

问题描述

我尝试使用GeoCoordinateWatcher类获取设备当前坐标并传入天气API查询,但安装System.Device.Location.Portable包后出现以下构建错误:

C:\Work\GitHub\WeatherPanel\MainWindow.xaml.cs(38,36,38,56): error CS0234: The type or namespace name 'GeoCoordinateWatcher' does not exist in the namespace 'System.Device.Location' (are you missing an assembly reference?)

同时收到警告:

warning NU1701: Package 'System.Device.Location.Portable 1.0.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net6.0-windows10.0.19041'. This package may not be fully compatible with your project.

请问如何解决该构建错误,或是否有其他NuGet包可使GeoCoordinateWatcher代码正常运行?

解决方案

1. 卸载不兼容的旧包

直接卸载System.Device.Location.Portable,这个包仅适配.NET Framework,和你的.NET 6 Windows应用目标框架完全不兼容,是导致错误的核心原因。

2. 选择适配目标框架的定位方案

方案A:用Windows官方原生定位API

针对net6.0-windows10.0.19041这类Windows桌面应用,优先使用Windows.Devices.Geolocation命名空间的API,这是微软为现代Windows平台提供的原生方案:

  • 右键项目→添加→引用→勾选Windows完成引用添加
  • 核心实现代码:
using Windows.Devices.Geolocation;

public async Task<Geocoordinate> GetCurrentCoordinateAsync()
{
    var accessStatus = await Geolocator.RequestAccessAsync();
    if (accessStatus != GeolocationAccessStatus.Allowed)
    {
        // 处理权限被拒绝的情况
        return null;
    }

    var locator = new Geolocator { DesiredAccuracy = PositionAccuracy.High };
    var position = await locator.GetGeopositionAsync();
    return position.Coordinate;
}

方案B:用跨平台定位包(支持多端)

如果后续需要扩展到其他平台(如Android、iOS),可以使用Microsoft.Maui.Essentials:

  • 安装NuGet包Microsoft.Maui.Essentials
  • 核心实现代码:
using Microsoft.Maui.Essentials;

public async Task<Location> GetCurrentLocationAsync()
{
    try
    {
        var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
        var location = await Geolocation.Default.GetLocationAsync(request);
        
        return location;
    }
    catch (FeatureNotSupportedException)
    {
        // 设备不支持定位功能
    }
    catch (PermissionException)
    {
        // 用户拒绝了定位权限
    }
    catch (Exception)
    {
        // 处理其他异常
    }
    return null;
}

方案C:兼容原有GeoCoordinateWatcher代码

如果想尽量复用原有代码逻辑,可以安装NuGet包System.Device(注意不是Portable版本),这个包是官方针对.NET Standard/.NET Core的适配版本,能让GeoCoordinateWatcher在.NET 6 Windows环境下正常运行,但要注意它的跨平台支持有限,仅推荐在Windows专属项目中使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:55:13