如何从url中读取csv文件?

问题描述:

我试图创建一个web服务,它获得一个URL,例如www.domain.co.uk/prices.csv然后读取csv文件。这是可能的和如何?理想情况下,没有下载csv文件?如何从url中读取csv文件?

+0

没有下载CSV文件?你期望如何阅读它?或者,你的意思是阅读它的一部分,而不必首先下载整件事情。 –

+0

你想做那个客户端或服务器端吗? – miniBill

+1

下载并不意味着你必须将文件保存到磁盘,如果这是你的想法。这就是说,你不能在没有下载文件的情况下阅读文件。 – Botz3000

你可以使用:

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<string> splitted = new List<string>(); 
    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是一个很好的。

+1

如果你正在将整个文件读入字符串,并且不需要'WebRequest'的额外灵活性,那么你可以使用' WebClient.DownloadString'。 – Joey

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

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

// 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类来下载文件,像这样(我没有进行任何异常处理,没有使用或关闭/处置调用,只是想给出您可以使用的想法和细化/提高...)

using System.Net; 

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

,那么你可以做任何你喜欢它,一旦文件内容在服务的执行流程是可用的。

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

+0

hmmmm所以如果我想把csv放到一个数据表中,我会做datatable table = webClient – Beginner

WebRequest的文档有一个使用流的示例。使用流允许您解析文档,而无需将其存储的所有内存

Sebastien Lorion's 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 
     } 
    } 

} 

ever popular FileHelpers,您还可以直接从流中读取。