从Xamarin升级到MAUI后,Share.Default.RequestAsync()抛出未实现异常
异常信息
Microsoft.Maui.ApplicationModel.NotImplementedInReferenceAssemblyException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.
at Microsoft.Maui.ApplicationModel.DataTransfer.ShareImplementation.PlatformRequestAsync(ShareFileRequest request) in /_/src/Essentials/src/Share/Share.netstandard.tvos.watchos.cs:line 11
at Microsoft.Maui.ApplicationModel.DataTransfer.ShareImplementation.RequestAsync(ShareFileRequest request)
解决方案步骤
1. 统一并重新安装MAUI Essentials NuGet包
- 确认项目仅引用
Microsoft.Maui.Essentials,移除旧版Xamarin.Essentials相关引用。 - 卸载当前
Microsoft.Maui.Essentials包,删除项目根目录下的bin、obj文件夹,清理NuGet缓存后重新安装最新稳定版。 - 检查项目文件(.csproj),确保该包版本唯一,无冲突配置。
2. 配置Android权限与文件路径
Android 14对文件访问权限限制严格,应用私有目录(SpecialFolder.Personal)的文件无法被其他应用读取,直接分享会触发异常:
- 添加权限:在
AndroidManifest.xml中加入对应权限:
Android 13+需手动在应用设置中授予「所有文件访问权限」,或在代码中动态请求权限。<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="32" /> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" android:minSdkVersion="33" /> - 切换到公共存储路径:将文件复制到公共目录(如下载目录)后再分享,示例代码:
// 获取应用私有目录文件路径 string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); string privateFilePath = System.IO.Path.Combine(documentsPath, "SomeRandomFile.txt"); // 检查文件是否存在 if (!File.Exists(privateFilePath)) { // 处理文件不存在逻辑 return; } // 获取公共下载目录 var publicDownloadDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads); string publicFilePath = Path.Combine(publicDownloadDir.AbsolutePath, "SomeRandomFile.txt"); // 复制文件到公共目录 File.Copy(privateFilePath, publicFilePath, overwrite: true); // 创建分享请求并执行 var shareRequest = new ShareFileRequest { Title = "Share file", File = new ShareFile(publicFilePath) }; try { await Share.Default.RequestAsync(shareRequest); // 分享完成后可删除公共目录的文件 File.Delete(publicFilePath); } catch (Exception ex) { string message = ex.Message; }
3. 验证项目配置
- 确认项目的Android目标框架为API 34(Android 14),项目文件中配置:
<TargetFrameworks>net8.0-android34.0</TargetFrameworks> - 清理并重新生成解决方案,重启Visual Studio后测试。
4. 排查自定义实现冲突
检查是否有自定义的Share服务实现或依赖注入配置覆盖了MAUI默认的Share.Default实例,确保使用官方提供的平台实现。
内容的提问来源于stack exchange,提问作者Mateusz Haex

