Необходимо добавить строки в Google Sheet в C#, получая ошибку «Поток не читается» - PullRequest
0 голосов
/ 22 января 2020

Итак, я пытаюсь проработать этот урок для добавления строк в Google Sheet: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append

Я получил свой файл «учетные данные. json» из более ранней версии. учебник: https://developers.google.com/sheets/quickstart/dotnet#step_3_set_up_the_sample

Я также использовал этот второй учебник для создания области, но я изменил параметр с «SpreadsheetsReadonly» на «Spreadsheets»:

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
static string ApplicationName = "Google Sheets API .NET Quickstart";

Я также использовал второй учебник для ссылки на файл «учетные данные. json», но я изменил параметры FileMode и FileAccess на «Append» и «Write»:

UserCredential credential;

using (var stream =
    new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
...
    Console.WriteLine("Credential file saved to: " + credPath);
}

Проблема: Когда я запускаю программу, я получаю следующую ошибку:

System.ArgumentException: «Поток не читается».

В результате отладки у меня сузил проблему до следующей строки:

new FileStream("credentials.json", FileMode.Append, FileAccess.Write))

Когда я изменяю ее на:

new FileStream("credentials.json", FileMode.Open, FileAccess.ReadWrite))

или любую другую конфигурацию "FileMode.foo", я не получаю исключения, и, как и ожидалось, всплывает окно с запросом разрешения на доступ API Google Sheets к моему листу. с.

Так в чем же дело? Есть ли какие-то настройки, которые мне нужно включить, чтобы разрешить входящим запросам добавлять строки на листы?


Это мой полный код:

using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Newtonsoft.Json;
using Data = Google.Apis.Sheets.v4.Data;
using System.Threading;
using Google.Apis.Util.Store;
using System.IO;

namespace ConsoleApp4
{
class Program
{
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
    static string[] Scopes = { SheetsService.Scope.Spreadsheets };
    static string ApplicationName = "Google Sheets API .NET Quickstart";

    public static void Main(string[] args)
    {
        SheetsService sheetsService = new SheetsService(new BaseClientService.Initializer
        {
            HttpClientInitializer = GetCredential(),
            ApplicationName = "Google-SheetsSample/0.1",
        });

        // The ID of the spreadsheet to update.
        string spreadsheetId = "3m83oibDdSiufaFA8Gba-f8afsonasiofafo3J-9UDe4";  // changed

        // The A1 notation of a range to search for a logical table of data.
        // Values will be appended after the last row of the table.
        string range = "A2:A5";  // TODO: Update placeholder value.

        // How the input data should be interpreted.
        SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum valueInputOption = (SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum)0;  // TODO: Update placeholder value.

        // How the input data should be inserted.
        SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum insertDataOption = (SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum)0;  // TODO: Update placeholder value.

        // TODO: Assign values to desired properties of `requestBody`:
        Data.ValueRange requestBody = new Data.ValueRange();

        SpreadsheetsResource.ValuesResource.AppendRequest request = sheetsService.Spreadsheets.Values.Append(requestBody, spreadsheetId, range);
        request.ValueInputOption = valueInputOption;
        request.InsertDataOption = insertDataOption;

        // To execute asynchronously in an async method, replace `request.Execute()` as shown:
        Data.AppendValuesResponse response = request.Execute();
        // Data.AppendValuesResponse response = await request.ExecuteAsync();

        // TODO: Change code below to process the `response` object:
        Console.WriteLine(JsonConvert.SerializeObject(response));
    }

    public static UserCredential GetCredential()
    {
        UserCredential credential;

        using (var stream =
            new FileStream("credentials.json", FileMode.Append, FileAccess.Write))
        {
            // The file token.json stores the user's access and refresh tokens, and is created
            // automatically when the authorization flow completes for the first time.
            string credPath = "token.json";
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        return credential;
    }
}
}
...