-2

I know it's kinda a silly question but i've read a lot of forums and nothing didn't work for me. ("https://www.nasdaq.com/api/v1/historical/HPQ/stocks/2010-11-14/2020-11-14") I got url where i need to download csv file. When i paste this url into browsers it works fine but when i paste it in my app it doesnt' work at all. My app just stop responding and create empty file.

WebClient webClient = new WebClient();
webClient.DownloadFile(
    "https://www.nasdaq.com/api/v1/historical/HPQ/stocks/2010-11-14/2020-11-14",
    @"HistoryDataStocks.csv");   
Clemens
  • 123,504
  • 12
  • 155
  • 268
Vlad
  • 419
  • 1
  • 10
  • 21
  • You could try using `HttpClient`, otherwise check out this similar question for some pointers. https://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c?rq=1 – Timothy Macharia Nov 14 '20 at 18:16
  • Set the request headers as shown in the answer to the duplicate question. And consider migrating to HttpClient. Microsoft discourages the use of WebClient. – Clemens Nov 14 '20 at 19:09

1 Answers1

0

You need send the proper web request. Try this code and it will work:

var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 30000;
request.AllowWriteStreamBuffering = false;

using (var response = (HttpWebResponse)request.GetResponse())
using (var s = response.GetResponseStream())
using (var fs = new FileStream("test.csv", FileMode.Create))
{
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
    {
        fs.Write(buffer, 0, bytesRead);
        bytesRead = s.Read(buffer, 0, buffer.Length);
    }
}

The file stream will contain your file.

bre_dev
  • 562
  • 3
  • 21
  • This does not work any better than the far more simple code in the question. Haven't you tried the URL from the question? – Clemens Nov 14 '20 at 18:37
  • It is a different way to do it that works. – bre_dev Nov 14 '20 at 18:39
  • Try it with the URL from the question to see that it does not work. And it is not only different, but also more complex without reason. It makes no sense to do this. This is what we did before we had WebClient and HttpClient. Today it is more or less obsolete. – Clemens Nov 14 '20 at 18:44
  • Thank you so much for answer) But unfortunately it didn't work for me i got exception(: System.Net.WebException: "Operation timeout expired" – Vlad Nov 14 '20 at 19:05