无法使用C#从Internet打开CSV文件

我是C#的新手。 我已编写代码从本地计算机上的文档中打开CSV文件。 它运行良好,数据解析工作。 麻烦的是,当我更改代码以从互联网站点打开文件时,我无法让它工作。 我可以使用VBA打开此文件,但我现在想使用C#ADO.NET。 我无法通过Google搜索找到答案。 任何人都可以帮助代码和/或指向一个有良好教程的网站。 所有人都非常感谢。 附上代码,我确定问题出在第24 – 26行;

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // // Read in a file line-by-line, and store it all in a List. // int i = 0; DateTime dte; List list = new List(); float[] Prices = new float[4]; WebClient wc = new WebClient(); byte[] data = wc.DownloadData("http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX"); using (StreamReader reader = new StreamReader(wc)) { string line; while ((line = reader.ReadLine()) != null) { //list.Add(line); // Add to list. Console.WriteLine(line); // Write to console. string[] parts = line.Split(','); int DateSetter = 1; int DateDone = 0; int CountFloat = 0; int PricesDone = 0; Double Volume = 0; foreach (string part in parts) { Console.WriteLine("{0} : {1}", i, part); if (DateSetter == 1) { dte = DateTime.Parse(part); DateSetter = 2; Console.WriteLine(dte); } if (DateDone == 1) { if (DateSetter < 6) { Prices[CountFloat] = float.Parse(part); CountFloat++; DateSetter++; Console.WriteLine(Prices[3]); } } DateDone = 1; if (PricesDone == 1) { Volume = double.Parse(part); Console.WriteLine(Volume); } if (DateSetter == 6) { PricesDone = 1; } } } } Console.ReadLine(); } } } 

您粘贴的代码无法编译。 但是,您可以使用WebClient下载到字符串,然后将字符串拆分为行:

 string content; using(WebClient wc = new WebClient()) content = wc.DownloadString("http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX"); foreach(var line in content.Split(new string [] {Environment.NewLine}, StringSplitOptions.None)) { //... } 

另一种选择是在你正在做的时候下载数据,然后用MemoryStream包装它:

 WebClient wc = new WebClient(); byte[] data = wc.DownloadData( "http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX"); using (var ms = new MemoryStream(data)) { using (var reader = new StreamReader(ms)) { string line; while ((line = reader.ReadLine()) != null) { // do whatever } } } 

这比分割字符串的优点是它使用的内存要少得多。