Search code examples
c#google-apigoogle-drive-apiservice-accountsgoogle-api-dotnet-client

Get Folders via Google Drive Api


I am using following service code to retrieve folders of the users. I enabled the drive api and want to use service account...

There are folders in drive but Execute returns none.

What might be missing?

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

namespace GoogleDriveService.Business.Services;

public class GoogleApiDriveService
{
    private DriveService _driveService;

    public GoogleApiDriveService()
    {
        var credentialsFilePath = "myservice-12aaae22210a.json";
        GoogleCredential credential = GoogleCredential.FromFile(credentialsFilePath)
                                                      .CreateScoped([DriveService.Scope.Drive,
                                                                    DriveService.Scope.DriveFile,
                                                                    DriveService.Scope.DriveReadonly]);

        var initializer = new BaseClientService.Initializer { HttpClientInitializer = credential };
        _driveService = new DriveService(initializer);
    }

    public List<Google.Apis.Drive.v3.Data.File> GetFolders()
    {
        var request = _driveService.Files.List();
        request.IncludeItemsFromAllDrives = true;
        request.SupportsAllDrives = true;
        request.Q = "mimeType='application/vnd.google-apps.folder'";

        var result = request.Execute();
        return result.Files.ToList();
    }
}

I enabled the drive api, download the service account key, and run the code.

if i make a call to about i get a response...

var req = _driveService.About.Get();
req.Fields = "*";
var about = req.Execute();`

Solution

  • A service account is not you nor is it your users. It has its own drive account. Which has no folders on it until you create them, or give it access to data owned by someone else by sharing the data with it.

    Go to the users drive account and share it with the service account email address it will then have access to the data.