如何将Json文件添加到Xamarin Forms?

3

当我试图获取用于Google认证凭据的Json文件时,出现了“文件未找到”错误。

            using (var stream = new FileStream("client.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                    .CreateScoped(Scopes);
            }

            service = new SheetsService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

我尝试将文件存储在资产中并进行了尝试

Assets.Open ("client.json")

出现了相同的错误。

我错过了什么?

1个回答

7
使用 Xamarin.Essentials 包中的 OpenAppPackageFileAsync 方法。
using (var stream = await FileSystem.OpenAppPackageFileAsync("client.json"))
 {
    using (var reader = new StreamReader(stream))
    {
        var fileContents = await reader.ReadToEndAsync();
    }
 }

Android:

在Android项目中的资产文件夹中将Build Action标记为AndroidAsset,以便使用OpenAppPackageFileAsync。

iOS:

在iOS项目中的资源文件夹中将Build Action标记为BundledResource,以便使用OpenAppPackageFileAsync。

相关信息请参考:https://learn.microsoft.com/en-us/xamarin/essentials/file-system-helpers?context=xamarin%2Fxamarin-forms&tabs=android#platform-implementation-specifics


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接