【问题标题】:C# Google Drive API list of files from my personal driveC# Google Drive API 我个人驱动器中的文件列表
【发布时间】:2016-03-15 23:34:44
【问题描述】:

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

我做了什么:

  1. 安装了所有需要的 NuGet 包
  2. 在 Google Developers Console 的 API 管理器中添加了 Google Drive
  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);
    

此代码似乎运行良好。问题是我只返回了一个文件,它被命名为“Getting started.pdf”,我不知道它是从哪里来的。我认为问题显然是我的个人 Google Drive 帐户没有连接到此代码。如何获得此调用以从我的个人 Google Drive 帐户返回文件?

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

【问题讨论】:

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


    【解决方案1】:

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

    解决方案 1:

    将一些文件上传到服务帐户谷歌驱动器帐户

    解决方案 2:

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

    评论更新:打开 google drive 网站。右键单击文件夹单击与他人共享。添加服务帐户电子邮件地址。繁荣它可以访问。

    解决方案 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);
        }
    }
    

    【讨论】:

    • 非常感谢您的回答!解决方案 1 不是一个选项,但其他两个听起来很完美。解决方案 2 的警告对我来说不是问题,因为我不希望遍历根 Google Drive 目录。
    • 只要您不更改使用 Oauth2 发送的用户名,将使用相同的凭据,但凭据仍可能失败。如果可以的话,我真的会选择 nr 2。
    • 它是一个虚拟用户,它没有密码,你不能像那样登录。密码更像是您从谷歌下载的密钥文件,它只能通过 API 访问。如果有人获得密钥文件和服务帐户电子邮件地址,他们可以使用 API 访问您的驱动器帐户。这又不是通过网站。服务帐号只能以编程方式使用
    • 我写的教程比你想知道的更多信息daimto.com/google-developer-console-service-account
    • 现在您知道如果遇到困难该去哪里找我。目前还没有太多关于 .net 的驱动器 v3 的文档,但是如果您遇到困难,我有一些示例内容可以尝试。
    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    相关资源
    最近更新 更多