如何在安装了WPF的应用程序中从谷歌驱动器下载文件
本文关键字:谷歌 驱动器 文件 下载 应用程序 安装 WPF | 更新日期: 2023-09-27 18:10:01
我正在开发WPF应用程序,并且在此我正在实现具有上传和下载功能的Google Drive API。上传工作正常,但我在下载文件时遇到了问题。我查看了谷歌文档中的代码https://developers.google.com/drive/web/manage-downloads
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)Unauthorized."。
所以请提供相同的代码在WPF应用程序或我如何从谷歌驱动器下载任何类型的文件。
根据文档,您需要下载新的google . api . auth内核包。之后,执行以下步骤
- 访问Google api控制台
- 如果这是你的第一次,点击"创建项目…"
- 否则,点击左上角"Google api"标志下的下拉菜单,然后点击"其他项目" 下的"创建…"
- 点击"API Access",然后点击"Create an OAuth 2.0 Client ID…"
- 输入产品名称,点击"下一步"。
- 选择"Installed application",点击"Create client ID"。
- 在新创建的"客户端ID for installed applications"中,将客户端ID和客户端秘密复制到adsensessample .cs文件中。
- 为你的项目激活驱动API
参考Google api 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 api的示例应用程序