【问题标题】:how can I download Google Drive file in compressed format in c#如何在 C# 中以压缩格式下载 Google Drive 文件
【发布时间】:2018-12-28 07:55:49
【问题描述】:

我正在尝试通过下载压缩格式的谷歌驱动器文件来提高我的应用程序的性能。我以此为参考。

https://developers.google.com/drive/api/v2/performance#gzip

我在发送的 HttpwebRequest 的标头中尝试了各种方法,但未能成功。任何人都可以在这方面帮助我。 这是我正在使用的代码。

    public void DownloadFile(string url, string filename)
    {
        try
        {
            var tstart = DateTime.Now;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Timeout = 60 * 1000; // Timeout
            request.Headers.Add("Authorization", "Bearer" + " " + AuthenticationKey);                
            request.Headers.Add("Accept-Encoding", "gzip,deflate");
            request.UserAgent = "MyApplication/11.14 (gzip)";                

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string content = response.GetResponseHeader("content-disposition");
            Console.WriteLine(content);

            System.IO.Stream received = response.GetResponseStream();
            using (System.IO.FileStream file = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                received.CopyTo(file);
            }

            var tend = DateTime.Now;
            Console.WriteLine("time taken to download '{0}' is {1} seconds", filename, (tend - tstart).TotalSeconds);
        }
        catch (WebException e)
        {
            Console.WriteLine("Exception thrown - {0}", e.Message);
        }
    }

【问题讨论】:

  • 你的错误是什么?
  • @DalmTo 没有错误,但我希望这里有一个压缩文件而不是常规文件,希望能提高下载速度。正如您回答的那样,我猜文件数据没有被压缩。你知道将来是否会支持这样的东西吗?还有其他更好的方法来提高下载速度吗?
  • 下载文件本身时不会。它的下载速度取决于您的连接、一天中的时间以及您设法连接到谷歌数据中心的服务器。

标签: c# google-drive-api user-agent system.net.httpwebrequest http-accept-encoding


【解决方案1】:

使用gzip

减少每个请求所需带宽的一种简单方便的方法是启用 gzip 压缩。虽然这需要额外的 CPU 时间来解压缩结果,但与网络成本的权衡通常非常值得。

为了接收 gzip 编码的响应,您必须做两件事:设置 Accept-Encoding 标头,并修改您的用户代理以包含字符串 gzip。以下是启用 gzip 压缩的正确格式的 HTTP 标头示例:

Accept-Encoding: gzip
User-Agent: my program (gzip)

Gzip 压缩来自 API 的实际响应。不是您正在下载的实际文件。例如file.export 返回一个file.resource json 对象,该对象将被压缩。不是您需要下载的文件的实际数据。文件以相应的类型下载manage downloads 虽然 google 可能能够在您下载时将 google doc 文件转换为 ms word 文件。它不会将 google doc 文件转换为 zip 文件,以便您可以下载压缩文件。

【讨论】:

  • @DalmTo 感谢您的回复。我回答了上面的问题。如果可以在文档中提及它以使其更加清晰,那将是很好的。 :)
  • 很明显,因为它在文档中没有提到它只会压缩文件本身只是响应对象。 Google 通常不会记录他们不支持的内容,如果他们这样做了,那么文档将没有尽头。
猜你喜欢
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
相关资源
最近更新 更多