0

以下のコードを使用して、Google ドライブからファイルをダウンロードしようとしています。

     public static Boolean downloadFile(string downloadurl, string _saveTo)
        {

            if (!String.IsNullOrEmpty(downloadurl))
            {
                try
                {
                  var x = service.HttpClient.GetByteArrayAsync(downloadurl);
                    byte[] arrBytes = x.Result;
                    System.IO.File.WriteAllBytes(_saveTo, arrBytes);
                    return true;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return false;
                }
            }
            else
            {
                // The file doesn't have any content stored on Drive.
                return false;
            }
        }

上記のコードをデバッグすると、次のように例外がスローされます。

?service.HttpClient.GetByteArrayAsync(downloadurl)
Id = 10, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
    AsyncState: null
    CancellationPending: false
    CreationOptions: None
    Exception: null
    Id: 10
    Result: null
    Status: WaitingForActivation

Google API コンソールを使用して作成したサービス アカウントから実行しようとしています。

例外の詳細は次のとおりです。

System.NullReferenceException was caught
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=System.Net.Http
  StackTrace:
       at System.Net.Http.Headers.HttpRequestHeaders.AddHeaders(HttpHeaders sourceHeaders)
       at System.Net.Http.HttpClient.PrepareRequestMessage(HttpRequestMessage request)
       at System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
       at System.Net.Http.HttpClient.GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
       at System.Net.Http.HttpClient.GetContentAsync[T](Uri requestUri, HttpCompletionOption completionOption, T defaultValue, Func`2 readAs)
       at System.Net.Http.HttpClient.GetByteArrayAsync(Uri requestUri)
       at System.Net.Http.HttpClient.GetByteArrayAsync(String requestUri)
4

2 に答える 2

0

Google .net クライアント ライブラリを使用したコード

サービス アカウント:

string[] scopes = new string[] {DriveService.Scope.Drive}; // Full access

var keyFilePath = @"c:\file.p12" ;    // Downloaded from https://console.developers.google.com
var serviceAccountEmail = "xx@developer.gserviceaccount.com";  // found https://console.developers.google.com

//loading the Key file
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) {
                                                   Scopes = scopes}.FromCertificate(certificate));

ドライブ サービスの作成

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

files.listを使用して、ドライブ上のすべてのファイルを一覧表示できます。

FilesResource.ListRequest request = service.Files.List();
request.Q = "trashed=false";
title = 'hello'
FileList files = request.Execute();

返されたアイテムをループして、必要なファイルを見つけます。それはファイルリソースです。それを次のメソッドに渡して、ファイルをダウンロードできます

/// <summary>
        /// Download a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/get
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_fileResource">File resource of the file to download</param>
        /// <param name="_saveTo">location of where to save the file including the file name to save it as.</param>
        /// <returns></returns>
        public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
        {

            if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
            {
                try
                {
                    var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl );
                    byte[] arrBytes = x.Result;
                    System.IO.File.WriteAllBytes(_saveTo, arrBytes);
                    return true;                  
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return false;
                }
            }
            else
            {
                // The file doesn't have any content stored on Drive.
                return false;
            }
        }

Googleドライブ認証C#から切り取ったコード

于 2015-08-26T08:37:31.453 に答える