Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading by C# with indirect url

I have an indirect link that generates an excel file. I searched a lot and found some methods that did not do what I needed. The link address does not refer to the excel file directly, the cause is that whenever the URL is requested the webpage make a new excel file __refreshes the contents. I've used different ways which are mentioned below. What I exactly want to do is that without opening a browser I want to download the content of the URL (which is an excel file) and save that as an excel file. Here is the link, which if you click on it, you will get an excel file directly, but the URL itself does not contain the extension of excel files.
I have used the following method:

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

The above method saves the contents but unfortunately it can not be displayed by excel and I do not 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
}

Also the above code was used by searching but it did not provide what I needed, I used some third party dlls to save stream as excel file and again the saved file could not be opened by excel. I also have used Process.Start but it opened the browser. I do not want to open any browser.

like image 706
Green Falcon Avatar asked Dec 25 '22 17:12

Green Falcon


2 Answers

It is compressed stream. You should 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);
    }
}
like image 67
EZI Avatar answered Dec 31 '22 13:12

EZI


Credit to EZI for the good answer. Just tossing this out as an alternative. HttpWebRequest does have funcionality 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);
    }
}
like image 27
Cory Avatar answered Dec 31 '22 13:12

Cory