c# - 使用 C# 从 Google Drive 导出/下载文件会生成一个空的零字节文件
问题描述
我正在尝试使用 C# 和 Google.Apis.Drive.v3 从 Google Drive 下载文件,但我得到了一个空的零字节文件(参见下面的代码)。我上传文件正常,但无法下载。任何帮助将不胜感激。
code
static string[] Scopes = { DriveService.Scope.Drive };
static string ApplicationName = "Test001";
private DriveService _service = null;
public async Task downloadFile(string url, string lstrDownloadFile)
{
// Authorize API access
UserCredential credential;
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Debug.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
_service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Attempt download
// Iterate through file-list and find the relevant file
FilesResource.ListRequest listRequest = _service.Files.List();
listRequest.Fields = "nextPageToken, files(id, name, mimeType, originalFilename, size)";
Google.Apis.Drive.v3.Data.File lobjGoogleFile = null;
foreach (var item in listRequest.Execute().Files)
{
if (url.IndexOf(string.Format("id={0}", item.Id)) > -1)
{
Debug.WriteLine(string.Format("{0}: {1}", item.OriginalFilename, item.MimeType));
lobjGoogleFile = item;
break;
}
}
FilesResource.ExportRequest request = _service.Files.Export(lobjGoogleFile.Id, lobjGoogleFile.MimeType);
Debug.WriteLine(request.MimeType);
MemoryStream lobjMS = new MemoryStream();
await request.DownloadAsync(lobjMS);
// At this point the MemoryStream has a length of zero?
lobjMS.Position = 0;
var lobjFS = new System.IO.FileStream(lstrDownloadFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
await lobjMS.CopyToAsync(lobjFS);
}
解决方案
可能只是没有在您的项目中启用 Drive API 一样简单。
我建议您添加以下代码。可能存在导致流无法填充的下载错误。
FilesResource.ExportRequest request = ...
request.MediaDownloader.ProgressChanged += progress =>
{
switch (progress.Status)
{
case DownloadStatus.Failed:
{
Console.WriteLine("Failed: " + progress.Exception?.Message);
break;
}
// other status case statements if you need them
}
};
MemoryStream lobjMS = ...
然后,您可以在 Failed 案例中放置断点或查看控制台中的异常。
推荐阅读
- python - 整数除以小数的结果是什么?
- php - 我想将 blog_id 发送到通过 Ajax 调用的页面。我怎样才能做到这一点?
- angular - 如何在syncfusion Grid组件中隐藏网格微调器
- reactjs - 如何使用 Flexbox 显示少数元素右对齐和左对齐
- android - 使用 androidX 的项目中的 ViewPager2 配置
- elixir - 将嵌套表单与 Ecto.Multis 和变更集结合使用
- swift - 有什么方法可以防止在一段时间后对变量进行更改?
- ios - UIKit 什么时候自动移除约束
- java - jdeps 在 fat jar 中使用 Java 11 和 JavaFX 失败
- java - 使用java spring boot jdbc模板执行oracle sql ddl statemenet后如何获得响应?