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

Xamarin跨平台应用编译Android报错:无法解析Windows.Foundation.UniversalApiContract引用

解决Xamarin Android编译时Windows.Foundation.UniversalApiContract引用错误的方案

核心思路

问题根源是你在代码中直接引用了UWP专属的Windows.Storage类及相关合约,而Android平台无法识别这些Windows专属API。解决的关键是隔离平台专属代码,让Android编译时完全跳过Windows相关的代码和引用。

1. 用条件编译隔离平台代码

在代码中通过平台编译指令,让不同平台只加载对应逻辑,Android编译时不会解析Windows的API引用:

// 仅在UWP平台加载Windows命名空间
#if WINDOWS_UWP
using Windows.Storage;
#endif

public void SaveLocalFile(string fileContent)
{
#if WINDOWS_UWP
    // UWP平台的文件写入逻辑
    var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    // 后续文件创建、写入代码
#elif ANDROID
    // Android平台的文件写入逻辑
    var localPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
    var fullFilePath = System.IO.Path.Combine(localPath, "your_file.txt");
    System.IO.File.WriteAllText(fullFilePath, fileContent);
#endif
}

2. 清理Android项目的无效引用

  • 右键Android项目 → 「管理NuGet程序包」,检查是否安装了UWP相关的包,如有直接卸载。
  • 打开Android项目的.csproj文件,查找是否存在<Reference Include="Windows.Foundation.UniversalApiContract"相关节点,找到后删除。

3. 可选:用Xamarin.Essentials统一跨平台操作

如果不想写平台专属代码,可以使用Xamarin.Essentials封装好的跨平台API,它会自动适配各平台的文件操作逻辑,无需依赖Windows专属合约:

using Xamarin.Essentials;
using System.IO;
using System.Threading.Tasks;

public async Task SaveFileCrossPlatform(string content)
{
    var targetPath = Path.Combine(FileSystem.AppDataDirectory, "target_file.txt");
    await File.WriteAllTextAsync(targetPath, content);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:16:55