我想创建一个包含特定股票价格的数组。
iStockTableRows
是股票的数量,例如“3”。
sSymbols
包含股票名称“AAPL + GOOG + MSFT”。
"http://finance.yahoo.com/d/quotes.csv?s=" + sSymbols + "&f=a"
是分成多行的股票价格。
WebRequest wrPrice = WebRequest.Create("http://finance.yahoo.com/d/quotes.csv?s=" + sSymbols + "&f=a"); //sSymbols zb. "AAPL+GOOG+MSFT"
WebResponse wResp = wrPrice.GetResponse();
StreamReader sr = new StreamReader(wResp.GetResponseStream());
double[] dCurrentPrice = new double[iStockTableRows];
int iLine = 0;
while (!sr.EndOfStream)
{
dCurrentPrice[iLine] = double.Parse(sr.ReadLine(), System.Globalization.CultureInfo.InvariantCulture);
iLine++;
}
sr.Close();
ReadLine()
由于某种原因没有返回任何内容,我在
System.FormatException
dCurrentPrice[iLine] = double.Parse(sr.ReadLine(), System.Globalization.CultureInfo.InvariantCulture);
因为那个。
答案 0 :(得分:0)
我实际上无法说出为什么你的方法不起作用。 我已经尝试发送请求,但收到长度为5的字符串,响应内容长度:7。看起来有一个BOM或类似的东西会产生一些从流中逐行读取的问题。
我会以这两种方式中的任何一种方式做到这一点。
StreamReader ReadToEnd()
string csvContent = sr.ReadToEnd();
然后解析这个。它看起来更安全方便。 看起来没有必要逐行阅读响应。
如果您确定响应是N个浮点数,请使用TryParse。 这对我有用:
string[] names = new [] {"AAPL", "GOOG", "MSFT"};
string url = String.Format("http://finance.yahoo.com/d/quotes.csv?s={0}&f=a", String.Join(",", names));
WebRequest wrPrice = WebRequest.Create(url);
WebResponse wResp = wrPrice.GetResponse();
StreamReader sr = new StreamReader(wResp.GetResponseStream());
double[] dCurrentPrice = new double[names.Length];
int iLine = 0;
while (!sr.EndOfStream)
{
double val;
if (double.TryParse(sr.ReadLine(),
System.Globalization.NumberStyles.AllowDecimalPoint,
System.Globalization.CultureInfo.InvariantCulture,
out val))
{
dCurrentPrice[iLine++] = val;
}
}
sr.Close();
Array.ForEach(dCurrentPrice, x => Console.WriteLine(x));
return;