0

我正在尝试使用以下代码从谷歌驱动器下载文件:

     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

1

你可以试试这个。
关联

using Google.Apis.Authentication;
    using Google.Apis.Drive.v2;
    using Google.Apis.Drive.v2.Data;

    using System.Net;

    public class MyClass {

      public static System.IO.Stream DownloadFile(
          IAuthenticator authenticator, File file) {
        if (!String.IsNullOrEmpty(file.DownloadUrl)) {
          try {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                new Uri(file.DownloadUrl));
            authenticator.ApplyAuthenticationToRequest(request);
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK) {
              return response.GetResponseStream();
            } else {
              Console.WriteLine(
                  "An error occurred: " + response.StatusDescription);
              return null;
            }
          } catch (Exception e) {
            Console.WriteLine("An error occurred: " + e.Message);
            return null;
          }
        } else {
          // The file doesn't have any content stored on Drive.
          return null;
        }
      }
    }
于 2015-08-26T07:19:47.993 回答
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 回答