C# How to download csv file from url

2.1k Views Asked by At

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");   
1

There are 1 best solutions below

4
bre_dev On

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.