Josh Stodola
Josh Stodola

Reputation: 82513

C# Google Drive API list of files from my personal drive

I am trying to connect to my own personal Google Drive account and gather a list of file names.

What I have done:

  1. Installed all the NuGet packages required
  2. Added Google Drive to the API Manager in Google Developers Console
  3. Setup a Service Account and downloaded a P12 key for authentication
  4. Wrote the following code to call the API:

    string EMAIL = "[email protected]";
    string[] SCOPES = { DriveService.Scope.Drive };
    StringBuilder sb = new StringBuilder();
    
    X509Certificate2 certificate = new X509Certificate2(@"c:\\DriveProject.p12",
                                   "notasecret", X509KeyStorageFlags.Exportable);
    ServiceAccountCredential credential = new ServiceAccountCredential(
       new ServiceAccountCredential.Initializer(EMAIL) { 
         Scopes = SCOPES 
       }.FromCertificate(certificate)
    );
    
    DriveService service = new DriveService(new BaseClientService.Initializer() { 
       HttpClientInitializer = credential
    });
    
    FilesResource.ListRequest listRequest = service.Files.List();
    IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
    if (files != null && files.Count > 0)
        foreach (var file in files)
            sb.AppendLine(file.Name);
    

This code seems to be working fine. The problem is I only get a single file returned, it is named "Getting started.pdf" and I have no idea where the hell it is coming from. I think the problem is clearly that my personal Google Drive account is not wired up to this code. How do I get this call to return the files from my personal Google Drive account?

The only help I was able to find was trying to get you to access any end users Google Drive account in your interface. My scenario is different than that. I only want to connect to my Google Drive account behind the scenes.

Upvotes: 2

Views: 4131

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117271

You are connecting with a service account which does not connect to your personal google drive account. Think of a service account as its own user, it has its own Google drive account. Which by running files.list apparently right now doesn't have any files on it.

Solution 1:

Upload some files to the Service accounts Google drive account

Solution 2:

Take the service account email address and share a folder on your google drive account with the service account like you would any other user. I am not sure if its possible to share a full drive account or not. Let me know if you manage to share the root folder :)

Update for comment: Open google drive the web site. right click the folder click share with others. Add the service account email address. Boom it has access.

Solution 3:

Switch to Oauth2 authenticate the code once where by you get a refresh token anytime you run the application there after just use that refresh token to gain access to your personal drive account.

Update for comment: You will have to authenticate it manually once. After that the client library will load the refresh token for you. Its stored on the machine.

Oauth2 Drive v3 sample code:

/// <summary>
/// This method requests Authentcation from a user using Oauth2.  
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static DriveService AuthenticateOauth(string clientSecretJson, string userName)
{
    try
    {
        if (string.IsNullOrEmpty(userName))
            throw new Exception("userName is required.");
        if (!File.Exists(clientSecretJson))
            throw new Exception("clientSecretJson file does not exist.");

        // These are the scopes of permissions you need. It is best to request only what you need and not all of them
        string[] scopes = new string[] { DriveService.Scope.Drive };                   // View and manage the files in your Google Drive         
        UserCredential credential;
        using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/apiName");

            // Requesting Authentication or loading previously stored authentication for userName
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                     scopes,
                                                                     userName,
                                                                     CancellationToken.None,
                                                                     new FileDataStore(credPath, true)).Result;
        }

        // Create Drive API service.
        return new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Drive Authentication Sample",
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine("Create Oauth2 DriveService failed" + ex.Message);
        throw new Exception("CreateOauth2DriveFailed", ex);
    }
}

Upvotes: 3

Related Questions