Не удается выполнить поиск файлов на Google Диске с служебной учетной записью

У меня есть учетная запись gmail, скажем, [email protected], я создал секрет клиента для использования API поиска Google Диска. С помощью этого примера кода я смог поиск и получение файлов с помощью моего консольного приложения. Но этот код сохраняет токен на локальном диске, поэтому для программной передачи учетных данных я создал Service Account, как указано в этом post.

Созданная мной учетная запись службы имеет следующие роли:

  1. Администратор сервисного аккаунта
  2. Администратор ключа сервисной учетной записи
  3. Создатель токена сервисного аккаунта
  4. Пользователь сервисной учетной записи
  5. Владелец

Но когда я пытаюсь получить файлы, используя учетную запись службы, он не возвращает файлы, хотя у меня есть файлы на диске моей учетной записи [email protected].

Вот мой код-

static void Main(string[] args)
{
    try
    {
        //var service = AuthenticateServiceAccountV2();
        var service = AuthenticateServiceAccountV1(GServiceAccount, "keycredentials.json");

        string pageToken = null;
        do
        {
            var request = service.Files.List();
            request.Q = $"name contains 'l'";
            request.Spaces = "drive";
            request.Fields = "nextPageToken, files(id, name, modifiedTime, fileExtension, webViewLink)";
            request.PageToken = pageToken;
            request.PageSize = 5;
            var result = request.Execute();
            foreach (Google.Apis.Drive.v3.Data.File file in result.Files)
            {

                var t = service.Files.Get(file.Id);
                Console.WriteLine(String.Format("Found file: {0} ({1}) Link for download: {2}", file.Name, file.Id, GenerateUrl(file.Id)));
            }
            pageToken = result.NextPageToken;
        } while (pageToken != null);
        Console.Read();
    }
    catch(Exception ex)
    {
        throw ex;
    }
}
static DriveService AuthenticateServiceAccountV1(string ServiceAccountEmail, string KeyFilePath)
{
    try
    {
        if (string.IsNullOrEmpty(KeyFilePath))
            throw new Exception("Path to the service account credentials file is required.");
        if (!File.Exists(KeyFilePath))
            throw new Exception("The service account credentials file does not exist at: " + KeyFilePath);
        if (string.IsNullOrEmpty(ServiceAccountEmail))
            throw new Exception("ServiceAccountEmail is required.");
        if (Path.GetExtension(KeyFilePath).ToLower() == ".json")
        {
            GoogleCredential credential;
            using (var stream = new FileStream(KeyFilePath, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                     .CreateScoped(Scopes);
            }
            return new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Drive Service account Authentication Sample",
            });
        }
        else if (Path.GetExtension(KeyFilePath).ToLower() == ".p12")
        {
            var certificate = new X509Certificate2(KeyFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(ServiceAccountEmail)
                {
                    Scopes = Scopes,
                }.FromCertificate(certificate));

            return new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName
            });
        }
        else
        {
            throw new Exception("Unsupported Service accounts credentials.");
        }
    }
    catch (Exception ex)
    {
        return null;
    }
}

person Sonali    schedule 20.03.2018    source источник
comment
Где вы можете поделиться файлами / папками с адресом электронной почты учетной записи службы, как указано в вашей ссылке?   -  person Mr.Rebot    schedule 20.03.2018
comment
@Mr.Rebot да, но это не соответствует моей потребности, поскольку я хочу выполнить поиск на диске пользователя, вошедшего в систему, в этом случае будет невозможно предоставить общий доступ к диску каждого пользователя с учетной записью службы.   -  person Sonali    schedule 21.03.2018