Search code examples
c#.netgoogle-apigoogle-drive-apigoogle-api-dotnet-client

Problem retrieving files in Google Drive using .NET SDK


I am using Google Drive SDK for the first time and based on some examples I came up with this code:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace GoogleDriveScanner;

class Program
{
    [STAThread]
    static async Task Main(string[] args)
    {
        string clientSecretJsonPath = "credentials.json";

        var clientSecrets = await GoogleClientSecrets.FromFileAsync(clientSecretJsonPath);

        var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            clientSecrets.Secrets,
            new[] { DriveService.ScopeConstants.DriveFile },
            "user",
            CancellationToken.None);

        var driveService = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "<<APP_NAME>>"
        });

        FilesResource.ListRequest listRequest = driveService.Files.List();
        listRequest.PageSize = 1000;
        listRequest.IncludeItemsFromAllDrives = true;
        listRequest.SupportsAllDrives = true;
        listRequest.Fields = "nextPageToken, files(id, name, size)"; 

        var files = listRequest.Execute().Files;
        if (files != null && files.Count > 0)
        {
            foreach (var file in files)
            {
                Console.WriteLine($"{file.Name} ({file.Size})");
            }
        }
        else
        {
            Console.WriteLine("No files found.");
        }

        Console.ReadLine();
    }
}

The problem is that the list always returns empty. I don't get any errors, seems like my Drive is empty, which is not the case.

What am I missing?


Solution

  • you have an async method i think you should be using the async form of the call as well

    var result = await service.Files.List().ExecuteAsync();
    
    foreach (var file in result.Files)
    {
        Console.WriteLine(file.Id);
    }
    

    Also unless you really need them you should remove

    listRequest.IncludeItemsFromAllDrives = true;
    listRequest.SupportsAllDrives = true;