0

Есть код:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using File = Google.Apis.Drive.v3.Data.File;

namespace DriveQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        static string[] Scopes = { DriveService.Scope.Drive};
        static string ApplicationName = "AppName";
        static string _uploadFile = @"file.txt";
        private static string FolderId = "id";
        static void Main(string[] args)
        {
            
            UserCredential credential;
            
            credential = GetUserCredential();
            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            

            IList<File> files = service.Files.List().Execute().Files;
            foreach (var file in files)
            {
                Console.WriteLine("File title: {0}  id: {1}");
            }
        }

        static void ReadAllFiles(DriveService service) 
        {

            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Files:");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine("{0} ({1})", file.Name, file.Id);
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();
        }
        static UserCredential GetUserCredential()
        {
            UserCredential userCredential;
            using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // 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 = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, "driveApiCredentials", "drive-credentials.json");

                userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }
            return userCredential;
        }
        
        static void FileUpload(DriveService _service, string FileName, string filePath, string contentType)
        {
            var FileMetaData = new Google.Apis.Drive.v3.Data.File();
            FileMetaData.Name = FileName;
            FileMetaData.Parents = new List<string> { FolderId };

            FilesResource.CreateMediaUpload request;
            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                request = _service.Files.Create(FileMetaData, stream, contentType);
                request.Upload();
            }
        }
    }
}

После компиляции открывается браузер в котором я выбираю аккаунт,и после это появляется окно с ошибкой: введите сюда описание изображения

Я хотел добавить url в настройках веб-приложения, но дело в том, что порт постоянно новый. Как убрать ошибку или указать в коде нужный порт?

3
  • Зачем вы хотел добавить url, какой и куда?
    – aepot
    3 июл 2021 в 16:57
  • Authorized redirect URIs в разделе Client ID for Web application
    – Andro 1
    3 июл 2021 в 17:01
  • 1
    Я не уверен, что вы можете использовать localhost или 127.0.0.1 в качестве редиректа. И вам гугл дал ссылку на документацию прямо на экране. Не рискну перепечатывать с картинки.
    – aepot
    3 июл 2021 в 17:05

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.