How do you create a new Google Drive Service in C# using OAuth

﹥>﹥吖頭↗ 提交于 2019-12-22 13:49:42

问题


I'm trying to write a simple command line application that will upload a file to Google Drive. I'm following along with the steps provided here: https://developers.google.com/drive/web/quickstart/quickstart-cs

The sample code they provide doesn't compile, specifically the line:

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

This returns the error:

"'Google.Apis.Services.BaseClientService.Initalizer' does not contain a definition for 'Authenticator'"

obviously the APIs have changed but I can't find the new way to do this.


回答1:


First off you are missing the autentication code. Also the tutorial you are refering to uses an older version of the libary if you are using apis.drive.v2 that wont work. This one works with the newer libarys: My Tutorial Google Drive api C# (there is also a winform sample project)

But heres some Examples of how you can get it working:

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

The code above will get you the User Credentials. It pops up a new browser window asking the user to autorise your app. My Tutorial here

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

The code above allow you to access the Drive Service. See how we send it the credential that we got from the Oauth call? Then to upload its a matter of calling 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);
}


来源:https://stackoverflow.com/questions/21569735/how-do-you-create-a-new-google-drive-service-in-c-sharp-using-oauth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!