我正在开发WPF应用程序,在此我正在实施具有上传和下载功能的Google Drive API。上传工作正常但我在下载文档时遇到问题。我查看了https://developers.google.com/drive/web/manage-downloads
中Google文档中的代码 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;
}
}
但根据这份文件 “https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis/Apis/Authentication/IAuthenticator.cs?r=e6585033994bfb3a24d4c140db834cb14b9738b2” 它显示“不再支持IAuthenticator”,因此上述代码无效。
我尝试使用UserCredential但它正在抛出“远程服务器返回错误:(401)未经授权。”。
因此,请在WPF应用程序中提供相同的代码,或者如何从Google驱动器下载任何类型的文件。
答案 0 :(得分:2)
根据文档,您需要下载新的Google.Apis.Auth nuget包。之后,请按照以下步骤进行操作
参考Google APIs Client Library for .NET
完成这些步骤后,您可以下载包含以下代码的文件
private async Task Run()
{
GoogleWebAuthorizationBroker.Folder = "Drive.Sample";
UserCredential credential;
using (var stream = new System.IO.FileStream("client_secrets.json",
System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None);
}
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
await UploadFileAsync(service);
// uploaded succeeded
Console.WriteLine("\"{0}\" was uploaded successfully", uploadedFile.Title);
await DownloadFile(service, uploadedFile.DownloadUrl);
await DeleteFile(service, uploadedFile);
}
private async Task DownloadFile(DriveService service, string url)
{
var downloader = new MediaDownloader(service);
downloader.ChunkSize = DownloadChunkSize;
// add a delegate for the progress changed event for writing to console on changes
downloader.ProgressChanged += Download_ProgressChanged;
// figure out the right file type base on UploadFileName extension
var lastDot = UploadFileName.LastIndexOf('.');
var fileName = DownloadDirectoryName + @"\Download" +
(lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : "");
using (var fileStream = new System.IO.FileStream(fileName,
System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
var progress = await downloader.DownloadAsync(url, fileStream);
if (progress.Status == DownloadStatus.Completed)
{
Console.WriteLine(fileName + " was downloaded successfully");
}
else
{
Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ",
fileName, progress.BytesDownloaded);
}
}
}
您可以为google drive apis下载sample application。