【问题标题】:How do you create a new Google Drive Service in C# using OAuth如何使用 OAuth 在 C# 中创建新的 Google Drive 服务
【发布时间】:2014-03-01 10:34:16
【问题描述】:

我正在尝试编写一个简单的命令行应用程序,它将文件上传到 Google Drive。我正在按照此处提供的步骤进行操作:https://developers.google.com/drive/web/quickstart/quickstart-cs

他们提供的示例代码无法编译,特别是以下行:

var service = new DriveService(new BaseClientService.Initializer()
            {
                Authenticator = auth
            });

这会返回错误:

“‘Google.Apis.Services.BaseClientService.Initalizer’不包含‘Authenticator’的定义”

显然 API 已更改,但我找不到执行此操作的新方法。

【问题讨论】:

    标签: c# oauth google-api google-drive-api google-oauth


    【解决方案1】:

    首先,您缺少身份验证代码。如果您使用的 apis.drive.v2 不起作用,您所指的教程也使用旧版本的库。这个适用于较新的库:My Tutorial Google Drive api C#(还有一个 winform 示例项目)

    但是这里有一些例子来说明如何让它工作:

    UserCredential credential; 
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
              new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
              new[] { DriveService.Scope.Drive,
                DriveService.Scope.DriveFile },
              "user",
              CancellationToken.None,
              new FileDataStore("Drive.Auth.Store")).Result; }
    

    上面的代码将为您提供用户凭据。它会弹出一个新的浏览器窗口,要求用户自动调整您的应用程序。 My Tutorial here

    BaseClientService service = new DriveService(new BaseClientService.Initializer()
     {
     HttpClientInitializer = credential,
     ApplicationName = "Drive API Sample",
     });
    

    上面的代码允许您访问云端硬盘服务。看看我们如何将我们从 Oauth 调用中获得的凭证发送给它?然后上传它的调用 service.files.insert

    // File's metadata.
    File body = new File();
    body.Title = "NewDirectory2";
    body.Description = "Test Directory";
    body.MimeType = "application/vnd.google-apps.folder";
    body.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
    try
       {
       FilesResource.InsertRequest request = service.Files.Insert(body);
       request.Execute(); 
      }
     catch (Exception e)
    {
    Console.WriteLine("An error occurred: " + e.Message);
    }
    

    【讨论】:

    • 这非常有帮助。谢谢!
    • 如果我已经拥有 access_token 并且不希望此弹出窗口进行用户授权怎么办?因为我想使用它服务器到服务器来访问用户的谷歌驱动程序以透明地保存文档。
    • 如何使用第二个示例,该示例使用无凭据的 DriveService 来访问我有可共享链接的公共共享文件夹?
    猜你喜欢
    • 2018-01-11
    • 2019-03-22
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多