Search code examples
c#exceldownloadwebclient

I get wrong file when I download it by C# code


When I open this excel file link in my browser, It will be downloaded successfully. But when I download it by the following c# code

private void downloadFile()
    {
        string remoteUri = "http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0";
        string fileName = @"g:\temp.xlsx";

        using (var client = new WebClient())
        {
            client.DownloadFile(remoteUri, fileName);
        }
    }

and I open it in the file explorer, I get the file format error:

enter image description here

What is wrong with my code?


Solution

  • Unzip file and write.

            string remoteUri = "http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0";
            string fileName = @"g:\temp.xlsx";
    
            using (var client = new WebClient())
            {
                using var stream = client.OpenRead(remoteUri);
                using var zipStream = new GZipStream(stream, CompressionMode.Decompress);
                using var resultStream = new MemoryStream();
                zipStream.CopyTo(resultStream);
                File.WriteAllBytes(fileName, resultStream.ToArray());
    
            }