如何从url读取csv文件?

我试图创建一个Web服务,访问URL,例如www.domain.co.uk/prices.csv ,然后读取csv文件。 这可能吗?怎么样? 理想情况下无需下载csv文件?

你可以使用:

 public string GetCSV(string url) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(resp.GetResponseStream()); string results = sr.ReadToEnd(); sr.Close(); return results; } 

然后拆分它:

 public static void SplitCSV() { List splitted = new List(); string fileList = getCSV("http://www.google.com"); string[] tempStr; tempStr = fileList.Split(','); foreach (string item in tempStr) { if (!string.IsNullOrWhiteSpace(item)) { splitted.Add(item); } } } 

虽然有很多CSV解析器,我建议不要滚动你自己的。 FileHelpers是一个很好的。

必须下载该文件才能阅读它。 这并不像你的代码可以以某种方式远程神圣内容而不提取它们。

但是如果你的意思是,你不需要将它保存到文件中。 您可以使用WebClient类来方便通过HTTP获取资源。 特别是您可能想要查看DownloadString方法 。

 // Download the file to a specified path. Using the WebClient class we can download // files directly from a provided url, like in this case. System.Net.WebClient client = new WebClient(); client.DownloadFile(url, csvPath); 

其中url是包含csv文件的站点,而csvPath是您希望实际文件的位置。

在您的Web服务中,您可以使用WebClient类来下载文件,类似于此(我没有进行任何exception处理,没有任何使用或关闭/处理调用,只是想提供您可以使用和改进/改进的想法。 ..)

 using System.Net; WebClient webClient = new WebClient(); webClient.DownloadFile("http://www.domain.co.uk/prices.csv"); 

然后,一旦文件内容在服务的执行流程中可用,您就可以使用它做任何事情。

如果必须将其作为Web服务调用的返回值返回给客户端,则可以返回DataSet或您喜欢的任何其他数据结构。

Sebastien Lorion的CSV Reader有一个构建器,它接受一个Stream。

如果您决定使用它,您的示例将变为:

 void GetCSVFromRemoteUrl(string url) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest HttpWebResponse response = request.GetResponse() as HttpWebResponse; using (CsvReader csvReader = new CsvReader(response.GetResponseStream(), true)) { int fieldCount = csvReader.FieldCount; string[] headers = csvReader.GetFieldHeaders(); while (csvReader.ReadNextRecord()) { //Do work with CSV file data here } } } 

广受欢迎的FileHelpers还允许您直接从流中读取。

WebRequest的文档有一个使用流的示例。 使用流可以解析文档而不将其全部存储在内存中