Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fancy way to load contents of a CSV file into a dictionary<string,string> in C#

Tags:

c#

file-io

linq

I know how to do this via streamreader and read to the end of line, but was curious if there was a fancier way of going it (for the sake of learing).

filename: blah.csv

File layout is simple:

"Some234234        ", 234
"blahblha234234    ", 2322

I want to load this into a dictionary (the second part should be a int, but I will parse later in case of errors).

Can you do this via linq somehow?

like image 239
mrblah Avatar asked Dec 10 '09 20:12

mrblah


2 Answers

You should use the TextFieldParser class in Microsoft.VisualBasic.dll. (There's nothing wrong with using it in C#.

Remember that CSV is a much more complicated file format than you think; both quotes and newlines can be escaped.

like image 173
SLaks Avatar answered Sep 28 '22 06:09

SLaks


CSV can be a lot more complicated than it appears at first. Here is an excellent library for reading CSV files.

http://www.codeproject.com/KB/database/CsvReader.aspx

like image 29
Samuel Neff Avatar answered Sep 28 '22 06:09

Samuel Neff