Search code examples
c#winformsdownloadwebclient

How to download a file from a URL using c#


I want to download a .xlsx file from below address. http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=1396-08-08

by clicking on the link automatically a file will be downloaded by the browser. I tried to download the file from this codes:

using (var client = new WebClient())
{
      client.DownloadFile("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=1396-08-08", @"D:\Archive\1396-08-08.xlsx");
} 

But it will download a weird file different from the file downloaded by the browser at first step.

Also I tried :

System.Diagnostics.Process.Start(
"http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");

But this code has two disadvantages:

1- It opens a browser which is not required.

2- I can't determine any path or file name for the downloaded file.

I want to gain exactly the same file that will be downloaded by clicking on the above link address. How can I download my required file?

Currupted file Correct File


Solution

  • Lasse Vågsæther Karlsen is correct. Your browser is smart enough to decompress the file because the response contains the header:

    content-encoding:"gzip"
    

    You can download and decompress the file with this code (adjust accordingly for your file name, path, etc.)

    void Main()
    {
        using (var client = new WebClient())
        {
            client.Headers.Add("accept", "*/*");
            byte[] filedata = client.DownloadData("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=1396-08-08");
    
            using (MemoryStream ms = new MemoryStream(filedata))
            {    
                using (FileStream decompressedFileStream = File.Create("c:\\deleteme\\test.xlsx"))
                {
                    using (GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(decompressedFileStream);
                    }
                }
            }
        }
    }