首页 > 解决方案 > 使用 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);
}

标签: c#apidownloadexportcloud

解决方案


可能只是没有在您的项目中启用 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 案例中放置断点或查看控制台中的异常。


推荐阅读