Download using C # with indirect URL

I have an indirect link that generates an excel file. I searched a lot and found several methods that did not do what I needed. The link address does not link directly to the excel file, the reason is that whenever a URL is requested, the web page creates a new excel file __refreshes the contents. I used different methods, which are described below. What I definitely want to do is that without opening the browser, I want to download the contents of the URL (which is an excel file) and save it as an excel file. Here is a link that, if you click on it, you will get the excel file directly, but the URL itself does not contain the excel file extension.
I used the following method:

client.DownloadFile(@"http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0", @"D:\a.xlsx");

The above method saves the content, but unfortunately it cannot be displayed using excel, and I don't know the reason.

WebRequest request = HttpWebRequest.Create(@"http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");
using (WebResponse response = request.GetResponse())
{
    Stream responseStream = response.GetResponseStream();
    StreamReader r = new StreamReader(responseStream);
    //third party methods
}

In addition, the above code was used in the search, but it did not provide me with what I needed, I used a third-party dllsto save the stream as an excel file, and again the saved file could not be opened by excel. I also used Process.Start, but it opened a browser. I do not want to open the browser.

+4
source share
2 answers

This is a compressed stream. You have to unzip it

WebRequest request = HttpWebRequest.Create(@"http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");
using (WebResponse response = request.GetResponse())
{
    Stream responseStream = response.GetResponseStream();
    using(var fs = File.Create("MarketWatchPlus-1394.4.24.xlsx"))
    {
        var zipStream = new System.IO.Compression.GZipStream(responseStream,  System.IO.Compression.CompressionMode.Decompress,true);
        zipStream.CopyTo(fs);
    }
}
+6
source

EZI loan for a good answer. Just drop it as an alternative. HttpWebRequest has functionality for automatic decompression.

HttpWebRequest request = WebRequest.Create(@"http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0") as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.GZip;
using (WebResponse response = request.GetResponse())
{
    using (Stream fs = File.Create("excelFile.xlsx"))
    {
        response.GetResponseStream().CopyTo(fs);
    }
}
+2
source

Source: https://habr.com/ru/post/1598076/


All Articles