Saurabh Agrawal
Saurabh Agrawal

Reputation: 1

how can I download Google Drive file in compressed format in c#

I am trying to improve performance for my application by downloading google drive files in compressed format. I am using this as reference.

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

I tried various things in the header of the HttpwebRequest I am sending , but couldnt achieve success. Can anyone please help me in this regard. This is the code I am using.

    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);
        }
    }

Upvotes: 0

Views: 989

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117254

Using gzip

An easy and convenient way to reduce the bandwidth needed for each request is to enable gzip compression. Although this requires additional CPU time to uncompress the results, the trade-off with network costs usually makes it very worthwhile.

In order to receive a gzip-encoded response you must do two things: Set an Accept-Encoding header, and modify your user agent to contain the string gzip. Here is an example of properly formed HTTP headers for enabling gzip compression:

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

Gzip compress the actual response from the API. Not the actual file you are downloading. For example file.export returns a file.resource json object this object would be compressed. Not the actual data of the file you will need to download. Files are downloaded in their corresponding type manage downloads While google may be able to convert a google doc file to a ms word file when you download it. It is not going to covert a google doc file to a zip file so that you can download it zipped.

Upvotes: 0

Related Questions