如何从URL中读取csv文件? [英] how to read a csv file from a url?

查看:1193
本文介绍了如何从URL中读取csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个网络服务,获取到一个网址,例如 www.domain.co.uk/prices.csv ,然后读取csv文件。这是可能和如何?理想情况下不下载csv文件?

Im trying to create a web service which gets to a URL e.g. www.domain.co.uk/prices.csv and then reads the csv file. Is this possible and how? Ideally without downloading the csv file?

推荐答案

您可以使用:

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 是一个不错的选择。

Though there are plenty of CSV parsers out there and i would advise against rolling your own. FileHelpers is a good one.

这篇关于如何从URL中读取csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆