C#Google Drive API个人驱动器中的文件列表

时间:2016-03-15 23:34:45

标签: .net google-api google-drive-api google-api-dotnet-client service-accounts

我正在尝试连接到我自己的个人Google云端硬盘帐户并收集文件名列表。

我做了什么:

  1. 安装了所有必需的NuGet包
  2. 将Google云端硬盘添加到Google Developers Console中的API Manager
  3. 设置Service Account并下载了用于身份验证的P12密钥
  4. 编写以下代码来调用API:

    string EMAIL = "myprojectname@appspot.gserviceaccount.com";
    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);
    
  5. 此代码似乎工作正常。问题是我只返回一个文件,它被命名为&#34; Getting started.pdf&#34;我不知道它到底是从哪里来的。我认为问题显然是我的个人Google云端硬盘帐户未连接到此代码。如何接听此电话以从我的个人Google云端硬盘帐户返回文件?

    我能找到的唯一帮助是尝试让您在界面中访问任何最终用户Google云端硬盘帐户。我的情况与此不同。我只想在幕后连接到我的 Google云端硬盘帐户。

1 个答案:

答案 0 :(得分:3)

您正在使用连接到您的个人Google云端硬盘帐户的服务帐户进行连接。将服务帐户视为自己的用户,它拥有自己的Google云端硬盘帐户。现在显然运行files.list并没有任何文件。

解决方案1:

将一些文件上传到服务帐户Google云端硬盘帐户

解决方案2:

获取服务帐户电子邮件地址,并像使用其他任何用户一样,使用服务帐户在Google云端硬盘帐户中共享文件夹。我不确定是否可以共享一个完整的驱动器帐户。如果您设法共享根文件夹,请告诉我们:)

评论更新:打开谷歌驱动网站。右键单击文件夹,单击与他人共享。添加服务帐户电子邮件地址。它有权访问。

解决方案3:

切换到Oauth2验证代码,只需在您使用该刷新令牌访问您的个人驱动器帐户后,只要您在那里运行应用程序就获得刷新令牌。

评论更新:您必须手动验证一次。之后,客户端库将为您加载刷新令牌。它存储在机器上。

Oauth2 Drive v3示例代码:

/// <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);
    }
}