gamble4846
gamble4846

Reputation: 53

How to add Json file to Xamarin Forms?

I Get an File not Found Error when i try to get Json file for Google Auth Creds

            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,
            });

i have tried to store file in assets and tried

Assets.Open ("client.json")

it gives out same error

what am i missing here?

Upvotes: 3

Views: 2390

Answers (1)

SushiHangover
SushiHangover

Reputation: 74164

Use OpenAppPackageFileAsync from the Xamarin.Essentials package.

using (var stream = await FileSystem.OpenAppPackageFileAsync("client.json"))
 {
    using (var reader = new StreamReader(stream))
    {
        var fileContents = await reader.ReadToEndAsync();
    }
 }

Android:

Assets folder in the Android project and mark the Build Action as AndroidAsset to use it with OpenAppPackageFileAsync

iOS:

Resources folder in the iOS project and mark the Build Action as BundledResource to use it with OpenAppPackageFileAsync.

re: https://learn.microsoft.com/en-us/xamarin/essentials/file-system-helpers?context=xamarin%2Fxamarin-forms&tabs=android#platform-implementation-specifics

Upvotes: 7

Related Questions