【问题标题】:how to read a csv file from a url?如何从 url 读取 csv 文件?
【发布时间】:2012-06-18 11:40:53
【问题描述】:

我正在尝试创建一个访问 URL 的 Web 服务,例如www.domain.co.uk/prices.csv 然后读取 csv 文件。这可能吗?如何?最好不要下载 csv 文件?

【问题讨论】:

  • 不下载 CSV 文件?你希望如何阅读它?还是您的意思是阅读其中的一部分而无需先下载整个内容。
  • 你想在客户端还是服务器端?
  • 下载并不意味着您必须按照您的想法将文件保存到磁盘。话虽如此,如果不下载文件,您将无法阅读该文件。

标签: c# csv


【解决方案1】:

你可以使用:

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 不错。

【讨论】:

  • 如果您将整个文件读入字符串并且不需要WebRequest 的额外灵活性,您可以使用WebClient.DownloadString
  • 如果您使用VisualBasic.IO.TextFieldParser,您可以通过添加对Microsoft.VisualBasic 的引用来使用已经内置在.NET 中的东西。之后使用它而不是流阅读器。 using (TextFieldParser parser = new TextFieldParser(response.GetResponseStream()))
【解决方案2】:
// 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 是您希望实际文件所在的位置。

【讨论】:

    【解决方案3】:

    在您的 Web 服务中,您可以使用 WebClient 类来下载文件,如下所示(我没有进行任何异常处理,没有任何 using 或 Close/Dispose 调用,只是想给出您可以使用和改进的想法/改善...)

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

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

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

    【讨论】:

    • hmmmm 所以如果我想把 csv 放到数据表中,我会做 datatable table = webClient
    【解决方案4】:

    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 还允许您直接从流中读取。

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 2013-04-23
        • 2017-11-10
        • 1970-01-01
        • 2013-06-13
        • 2019-05-27
        • 1970-01-01
        • 1970-01-01
        • 2019-04-17
        相关资源
        最近更新 更多