我正在尝试使用以下代码从谷歌驱动器下载文件:
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)
答案 0 :(得分:0)
你可以试试这个。
link
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;
}
}
}