Xamarin应用连接Google Firestore时找不到JSON凭证文件求助
Xamarin应用连接Google Firestore无法找到JSON凭证文件的解决方案
问题概述
Xamarin应用切换到Google.Cloud.Firebase和Google.Cloud.Firebase.V1包连接Firestore时,Windows平台正常运行,但移动端(Android/iOS)出现找不到JSON凭证文件的错误,报错提示无法找到/app-firebase-adminsdk.json,尝试修改路径和文件属性后仍未解决。
解决方法
方法1:直接从嵌入资源加载凭证(推荐)
移动平台的文件路径逻辑与桌面端差异较大,直接读取嵌入的凭证资源更可靠:
- 将JSON凭证文件的生成操作设置为
嵌入的资源,所有平台统一此设置 - 使用以下代码读取资源并创建Firestore实例:
using System.Reflection; using Google.Apis.Auth.OAuth2; using Google.Cloud.Firestore; // 替换为你的项目命名空间+文件名,例如"YourAppNamespace.app-firebase-adminsdk.json" string resourceName = $"{Assembly.GetExecutingAssembly().GetName().Name}.app-firebase-adminsdk.json"; using Stream credentialStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); if (credentialStream == null) { throw new FileNotFoundException("未找到嵌入的凭证资源,请检查资源名称是否正确"); } // 创建凭证并初始化FirestoreDb GoogleCredential credential = GoogleCredential.FromStream(credentialStream) .CreateScoped(FirestoreDb.DefaultScopes); FirestoreDb firestoreDb = new FirestoreDbBuilder { ProjectId = "appmobile", Credential = credential }.Build();
- 若不确定资源名称,可运行以下代码列出所有嵌入资源,确认正确的名称:
foreach (var resource in Assembly.GetExecutingAssembly().GetManifestResourceNames()) { Console.WriteLine(resource); }
方法2:通过文件路径加载(需适配移动平台)
如果坚持使用文件路径方式,需根据Android/iOS平台分别处理文件的存储路径:
Xamarin.Android 适配
- 将JSON文件的生成操作设为
内容,复制到输出目录设为始终复制 - 先将资产文件复制到应用可读写的目录,再加载:
using System.IO; using Android.App; string fileName = "app-firebase-adminsdk.json"; string destPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName); // 仅当文件不存在时复制 if (!File.Exists(destPath)) { using Stream assetStream = Application.Context.Assets.Open(fileName); using FileStream fileStream = new FileStream(destPath, FileMode.Create); assetStream.CopyTo(fileStream); } // 设置环境变量并创建Firestore实例 Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", destPath); FirestoreDb firestoreDb = FirestoreDb.Create("appmobile");
Xamarin.iOS 适配
- 将JSON文件的生成操作设为
BundleResource,复制到输出目录设为始终复制 - 获取Bundle内的文件路径并加载:
using Foundation; using System.IO; string fileName = "app-firebase-adminsdk.json"; string filePath = Path.Combine(NSBundle.MainBundle.BundlePath, fileName); Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", filePath); FirestoreDb firestoreDb = FirestoreDb.Create("appmobile");
内容的提问来源于stack exchange,提问作者Spack09
相关产品推荐
相关产品推荐

