在C#中解析CSV文件,带头 [英] Parsing CSV files in C#, with header
问题描述
有没有默认/官方/推荐的方式来解析C#中的CSV文件?我不想卷自己的解析器。
Is there a default/official/recommended way to parse CSV files in C#? I don't want to roll my own parser.
此外,我看到一些人使用ODBC / OLE DB通过文本驱动程序读取CSV,很多人由于其缺点而沮丧。这些缺点是什么?
Also, I've seen instances of people using ODBC/OLE DB to read CSV via the Text driver, and a lot of people discourage this due to its "drawbacks." What are these drawbacks?
理想情况下,我正在寻找一种通过列名读取CSV的方法,使用第一个记录作为标题/字段名。
Ideally, I'm looking for a way through which I can read the CSV by column name, using the first record as the header / field names. Some of the answers given are correct but work to basically deserialize the file into classes.
推荐答案
让一个库处理所有的nitty-细腻的细节为你! : - )
Let a library handle all the nitty-gritty details for you! :-)
查看 FileHelpers 并保持DRY - 不要重复自己 - 不需要重新发明轮子一个gazillionth时间....
Check out FileHelpers and stay DRY - Don't Repeat Yourself - no need to re-invent the wheel a gazillionth time....
你基本上只需要定义你的数据的形状 - 字段在CSV中的单独行中 - 通过公共类(以及精心设计的属性,如默认值,NULL值的替换等等),将FileHelpers引擎指向一个文件,bingo - 返回所有来自该文件的条目。一个简单的操作 - 伟大的性能!
You basically just need to define that shape of your data - the fields in your individual line in the CSV - by means of a public class (and so well-thought out attributes like default values, replacements for NULL values and so forth), point the FileHelpers engine at a file, and bingo - you get back all the entries from that file. One simple operation - great performance!
这篇关于在C#中解析CSV文件,带头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!