C# 使用身份验证服务帐户上载文件的Google API

C# 使用身份验证服务帐户上载文件的Google API,c#,google-api,google-drive-api,google-api-dotnet-client,service-accounts,C#,Google Api,Google Drive Api,Google Api Dotnet Client,Service Accounts,我试图通过API Google Drive发送文件,但是,我找不到任何关于如何使用身份验证服务帐户执行C#上传文件的文档 我下载了Daimto库,但是,当我们使用身份验证ClientId和ClientSecret时,他使用DriveService类上传。但使用帐户服务的身份验证,他返回到PlusService类,并没有发现以这种方式上传文件的方法 有人能帮我吗? 致意 使用身份验证服务帐户 public PlusService GoogleAuthenticationServiceAcc

我试图通过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;
    }
使用身份验证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类方法,使文件上载到google drive daimtologledriveHelper.uploadFile(_服务,文件名,item.NomeArquivo,目录ID)


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

我不确定您正在学习我的哪个教程。但是您的第一块代码是使用PlusService,您应该使用DriveService。您对Google drive API的任何请求都必须通过DriveService

使用服务帐户验证Google drive:

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

            }
        }
    }
//
///使用服务帐户向Google进行身份验证
///文件:https://developers.google.com/accounts/docs/OAuth2#serviceaccount
/// 
///从谷歌开发者控制台https://console.developers.google.com
///从Google开发者控制台下载的服务帐户密钥文件的位置https://console.developers.google.com
/// 
公共静态驱动器服务AuthenticateServiceAccount(字符串serviceAccountEmail,字符串keyFilePath)
{
//检查文件是否存在
如果(!File.Exists(keyFilePath))
{
WriteLine(“发生错误-密钥文件不存在”);
返回null;
}
//Google驱动器作用域文档:https://developers.google.com/drive/web/scopes
string[]scopes=新字符串[]{DriveService.Scope.Drive,//查看和管理文件和文档
DriveService.Scope.DriveAppdata,//查看和管理自己的配置数据
DriveService.Scope.DriveAppsReadonly,//查看您的驱动器应用程序
DriveService.Scope.DriveFile,//查看和管理此应用程序创建的文件
DriveService.Scope.DriveMetadataReadonly,//查看文件的元数据
DriveService.Scope.DriveReadonly,//查看驱动器上的文件和文档
DriveService.Scope.DriveScripts};//修改应用程序脚本
var证书=新的X509Certificate2(keyFilePath,“notasecret”,X509keystrageFlags.Exportable);
尝试
{
ServiceAccountCredential credential=新ServiceAccountCredential(
新ServiceAccountCredential.初始值设定项(serviceAccountEmail)
{
范围=范围
}.FromCertificate(证书));
//创建服务。
DriveService=新的DriveService(新的BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=“Daimto驱动API示例”,
});
回程服务;
}
捕获(例外情况除外)
{
Console.WriteLine(例如InnerException);
返回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;
            }           

        }
私有静态字符串GetMimeType(字符串文件名)
{
字符串mimeType=“应用程序/未知”;
字符串ext=System.IO.Path.GetExtension(文件名).ToLower();
Microsoft.Win32.RegistryKey regKey=Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if(regKey!=null&®Key.GetValue(“内容类型”)!=null)
mimeType=regKey.GetValue(“内容类型”).ToString();
返回mimeType;
}
/// 
///上载文件
///文件:https://developers.google.com/drive/v2/reference/files/insert
/// 
///有效的经过身份验证的驱动器服务
///要上载的文件的路径
///包含此文件的父文件夹的集合。
///设置此字段将把文件放在所有提供的文件夹中。根文件夹。
///如果上载成功,则返回上载文件的文件资源
///如果上载失败,则返回null
公共静态文件上传文件(DriveService\u服务、字符串\u上传文件、字符串\u父级){
if(System.IO.File.Exists(_uploadFile))
{
文件体=新文件();
body.Title=System.IO.Path.GetFileName(_uploadFile);
body.Description=“Diamto驱动样本上传的文件”;
body.MimeType=GetMimeType(_uploadFile);
body.Parents=new List(){new ParentReference(){Id=\u parent}};
//文件的内容。
byte[]byteArray=System.IO.File.ReadAllBytes(\u uploadFile);
System.IO.MemoryStream stream=新的System.IO.MemoryStream(byteArray);
尝试
{
fileResource.InsertMediaUpload请求=_service.Files.Insert(body、stream、GetMimeType(_uploadFile));
request.Upload();
返回request.ResponseBody;