Google API使用身份validation服务帐户上传文件

我正在尝试通过API Google Drive发送文件,但是,我找不到任何有关如何使用身份validation服务帐户执行C#上传文件的文档。

我下载了Daimto库,但是,当我们使用身份validationClientId和ClientSecret时,他使用DriveService类上传。 但是使用身份validation进行帐户服务后,他返回到PlusService类,发现无法以这种方式上传文件。

有人能帮我吗? 最好的祝福

使用validation服务帐户

public PlusService GoogleAuthenticationServiceAccount() { String serviceAccountEmail = "106842951064-6s4s95s9u62760louquqo9gu70ia3ev2@developer.gserviceaccount.com"; //var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable); var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { PlusService.Scope.PlusMe } }.FromCertificate(certificate)); // Create the service. var service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Plus API Sample", }); return service; } 

使用Authentication ClientId和ClientSecret

  public DriveService GoogleAuthentication(string userClientId, string userSecret) { //Scopes for use with the Google Drive API string[] scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile }; // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = userClientId, ClientSecret = userSecret }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Daimto.GoogleDrive.Auth.Store")).Result; DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Drive API Sample" }); return service; } 

Daimto类方法,使文件上传到谷歌驱动器DaimtoGoogleDriveHelper.uploadFile(_service,fileName,item.NomeArquivo,directoryId);

如您所见,Daimto库有一个上传方法,但是,使用_service参数,即DriveService类型,这是GoogleAuthentication方法返回的内容。 但GoogleAuthenticationServiceAccount方法返回PlusService类型,并且与DriveService类型不兼容。

我不确定你关注的是哪一个教程。 但是你的第一大块代码是使用PlusService,你应该使用DriveService。 您对Google云端硬盘API发出的任何请求都必须通过DriveService

使用服务帐户向Google云端硬盘进行身份validation:

 ///  /// Authenticating to Google using a Service account /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount ///  /// From Google Developer console https://console.developers.google.com /// Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com ///  public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) { // check the file exists if (!File.Exists(keyFilePath)) { Console.WriteLine("An Error occurred - Key file does not exist"); return null; } //Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents DriveService.Scope.DriveAppdata, // view and manage its own configuration data DriveService.Scope.DriveAppsReadonly, // view your drive apps DriveService.Scope.DriveFile, // view and manage files created by this app DriveService.Scope.DriveMetadataReadonly, // view metadata for files DriveService.Scope.DriveReadonly, // view files and documents on your drive DriveService.Scope.DriveScripts }; // modify your app scripts var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); try { ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the service. DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Daimto Drive API Sample", }); return service; } catch (Exception ex) { Console.WriteLine(ex.InnerException); return null; } } } 

上传一个文件:

 private static string GetMimeType(string fileName) { string mimeType = "application/unknown"; string ext = System.IO.Path.GetExtension(fileName).ToLower(); Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (regKey != null && regKey.GetValue("Content Type") != null) mimeType = regKey.GetValue("Content Type").ToString(); return mimeType; } ///  /// Uploads a file /// Documentation: https://developers.google.com/drive/v2/reference/files/insert ///  /// a Valid authenticated DriveService /// path to the file to upload /// Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder. /// If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null public static File uploadFile(DriveService _service, string _uploadFile, string _parent) { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = "File uploaded by Diamto Drive Sample"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile)); request.Upload(); return request.ResponseBody; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } } else { Console.WriteLine("File does not exist: " + _uploadFile); return null; } } 

如果您使用Oauth2或服务帐户,上传代码是相同的,没有区别。

代码从Github上的Google Drive .net示例中删除 : 带有C#.net的Google Drive API – 下载