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

时间:2015-02-26 15:04:33

标签: c# google-api google-drive-api google-api-dotnet-client service-accounts

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

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

有人能帮助我吗? 最好的问候

使用身份验证服务帐户

    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类型不兼容。

1 个答案:

答案 0 :(得分:1)

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

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

/// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// Uploads a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_uploadFile">path to the file to upload</param>
        /// <param name="_parent">Collection of parent folders which contain this file. 
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns>If upload succeeded returns the File resource of the uploaded file 
        ///          If the upload fails returns null</returns>
        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<ParentReference>() { 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云端硬盘.net示例中删除的代码 教程:Google Drive API with C# .net – Download

相关问题