-2

我知道这是一个愚蠢的问题,但我已经阅读了很多论坛,没有什么对我不起作用。(“https://www.nasdaq.com/api/v1/historical/HPQ/stocks/2010-11-14/2020-11-14”)我得到了需要下载 csv 文件的网址。当我将此网址粘贴到浏览器中时,它可以正常工作,但是当我将其粘贴到我的应用程序中时,它根本不起作用。我的应用程序只是停止响应并创建空文件。

WebClient webClient = new WebClient();
webClient.DownloadFile(
    "https://www.nasdaq.com/api/v1/historical/HPQ/stocks/2010-11-14/2020-11-14",
    @"HistoryDataStocks.csv");   
4

1 回答 1

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.

于 2020-11-14T18:16:42.300 回答