C# 如何从 url 读取 csv 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11082062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to read a csv file from a url?
提问by Beginner
Im trying to create a web service which gets to a URL e.g. www.domain.co.uk/prices.csvand then reads the csv file. Is this possible and how? Ideally without downloading the csv file?
我试图创建一个 Web 服务,它可以访问一个 URL,例如www.domain.co.uk/prices.csv,然后读取 csv 文件。这是可能的吗?理想情况下不下载 csv 文件?
采纳答案by dtsg
You could use:
你可以使用:
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;
}
And then to split it:
然后拆分它:
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);
}
}
}
Though there are plenty of CSV parsers out there and i would advise against rolling your own. FileHelpersis a good one.
尽管那里有很多 CSV 解析器,但我建议不要使用自己的解析器。FileHelpers是一个不错的选择。
回答by Joey
You have todownload the file to read it. It's not like your code could somehow divine the contents remotely without fetching them.
您必须下载该文件才能阅读它。这不像您的代码可以在不获取它们的情况下以某种方式远程占卜内容。
But you don't need to save it to a file if you mean that. You can use the WebClientclass as a convenience to fetch resources over HTTP. In particular you may want to look at the DownloadStringmethod.
但是,如果您是这个意思,则不需要将其保存到文件中。您可以使用WebClient该类来方便地通过 HTTP 获取资源。您可能特别想查看DownloadString方法。
回答by Shiven
// 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);
Where the url is your site with the csv file and the csvPath is where you want the actual file to go.
url 是带有 csv 文件的站点,而 csvPath 是您希望实际文件所在的位置。
回答by Davide Piras
In your Web Service you could use the WebClient class to download the file, something like this ( I have not put any exception handling, not any using or Close/Dispose calls, just wanted to give the idea you can use and refine/improve... )
在您的 Web 服务中,您可以使用 WebClient 类来下载文件,就像这样(我没有进行任何异常处理,没有任何 using 或 Close/Dispose 调用,只是想提供您可以使用和改进/改进的想法。 ..)
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://www.domain.co.uk/prices.csv");
then you can do anything you like with it once the file content is available in the execution flow of your service.
然后,一旦文件内容在您的服务的执行流程中可用,您就可以用它做任何您喜欢的事情。
if you have to return it to the client as return value of the web service call you can either return a DataSetor any other data structure you prefer.
如果您必须将其作为 Web 服务调用的返回值返回给客户端,您可以返回 aDataSet或您喜欢的任何其他数据结构。
回答by miniBill
The documentation for WebRequesthas an example that uses streams. Using a stream allows you to parse the document without storing it all in memory
WebRequest的文档有一个使用流的示例。使用流允许您解析文档而无需将其全部存储在内存中
回答by dash
Sebastien Lorion's CSV Readerhas a constructor that takes a Stream.
Sebastien Lorion 的 CSV Reader有一个接受 Stream 的构造函数。
If you decided to use this, your example would become:
如果您决定使用它,您的示例将变为:
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
}
}
}
The ever popular FileHelpersalso allows you to read directly from a stream.
在日益流行的FileHelpers,您还可以直接从流中读取。

