如何读取CSV并在C#中使用这些值 [英] How do I read a CSV and use those values in C#

查看:88
本文介绍了如何读取CSV并在C#中使用这些值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取用户从openFileDialog(C#Windows窗体)中选择的CSV,并访问每行中的值。我遇到的问题是如何获取该CSV的内容并使用它做一些事情。这是PowerShell中一个非常简单的过程(import-csv,然后使用foreach循环来处理每一行)。任何人都可以给我一些方向吗?



在C#中有很多关于CSV的帖子但是它们似乎都没有做我需要的东西而且他们都做了不一样。



谢谢!

I need to read a CSV that the user selects from an openFileDialog (C# Windows Form), and access the values in each row. The problem I am having is how to get the contents of that CSV and do something with it. This is a pretty straightforward process in PowerShell (import-csv, then use a foreach loop to process each row). Can anybody give me some direction on this?

There are a lot of posts surrounding CSV's in C# but none of them seem to do quite what I need and they all do it differently.

Thanks!

推荐答案

一个关键问题是你想要阅读的CSV文件始终具有相同的列数。如果文件的结构总是相同的,你可以使用Linq将文件解析为与行对应的IEnumerables集合。



或者你可以创建一个预定义的schema类来解析/映射数据。



如果每个文件的结构不同,那么你可能想要在DataTable中得到结果。 ..为此,有一个调整良好的旧库FileHelpers将为你遛狗:[ ^ ]。



有关使用FileHelpers的示例,请参阅此处:[ ^ ]。
A critical question is whether the CSV files you want to read always have the same number of columns. If the structure of the files is always the same, you can use Linq to parse the file into a collection of IEnumerables that will correspond to Rows.

Or, you can create a pre-defined "schema" Class to parse/map the data into.

If the structure of each file varies, then you probably want results in a DataTable ... for that there is a well-tuned old library, FileHelpers, that will "walk the dog" for you: [^].

See this for an example of using FileHelpers: [^].


这篇关于如何读取CSV并在C#中使用这些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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