Search code examples
c#webclient

DownloadFileAsync downloading corrupted file


I am trying to build a download class. Files from GitHub download fine, but if I download ROBLOX assets (http://www.roblox.com/asset/?id=1286103 as an example), it downloads a file filled with garbage data, when it should download a ROBLOX mesh file that starts with the header "version 1.00".

    public void InitDownload(string additionalText = "")
    {
        downloadOutcomeAddText = additionalText;

        saveFileDialog1 = new SaveFileDialog()
        {
            FileName = fileName,
            //"Compressed zip files (*.zip)|*.zip|All files (*.*)|*.*"
            Filter = fileFilter,
            Title = "Save " + fileName
        };

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    wc.DownloadProgressChanged += wc_DownloadProgressChanged;
                    wc.DownloadFileAsync(new Uri(fileURL), saveFileDialog1.FileName);
                }

                downloadOutcome = "File " + Path.GetFileName(saveFileDialog1.FileName) + " downloaded!" + downloadOutcomeAddText;
            }
            catch (Exception ex)
            {
                downloadOutcome = "Error when downloading file: " + ex.Message;
            }
        }
    }

    void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        downloadProgress.Value = e.ProgressPercentage;
    }

Solution

  • It looks like the ROBLOX API is responding with gzip encoded data and evidently WebClient.DownloadFileAsync doesn't default to automatically decompressing the response body. For more information and a somewhat dated example of how to handle this see: https://blog.codinghorror.com/netwebclient-and-gzip/.

    Update: This Stack Overflow answer may also be helpful (it is simpler and doesn't require a 3rd party library): Uncompressing gzip response from WebClient