Rich C Rich C - 1 year ago 199
C# Question

Get only first column values from CSV rows using CSVHelper

I am trying to parse a CSV file and extract the first string in each line, or the first column as it is laid out in MS Excel.
I am using

with the
method returning a
to the
The problem is, it is returning every single value, so my out looks like this for each line:

20070330 00:00 // This is the value I want to reference

How can I reference only the values at these positions in the file without putting in a counter to skip the interim values?

enter image description here

using (TextReader reader = File.OpenText(folder))
var datesInCsv = new List<string>();
var parsedCsv = new CsvParser(reader);
while (true)
var row = parsedCsv.Read();
if (row.IsNullOrEmpty())
foreach (var date in row)



Answer Source

The CsvHelper library you are using requires you pass a CsvConfiguration instance when you build the instance of a CsvParse class. This is important to let the library understand and correctly parse your line

The most important thing to give is the value for the Delimiter property. In other words the character used to separate one field from the next one.
You should look at your CSV file and put the appropriate value below.
(For this example I have used the semicolon but change it according to your file)

Looking at you code I think also that the configuration SkipEmptyRecords could be used to simplify the code.

using (TextReader reader = File.OpenText(folder))
    var datesInCsv = new List<string>();
    CsvConfiguration config = new CsvConfiguration();
    config.Delimiter = ";";
    config.SkipEmptyRecords = true;
    var parsedCsv = new CsvParser(reader, config);

    string[] row = null;
    while ((row = parsedCsv.Read()) != null)
        // This IsNullOrEmpty doesn't exist according 
        // to Intellisense and the compiler.
        // if(row.IsNullOrEmpty) 

        // At this point the row is an array of strings where the first
        // element is the value you are searching for. No need of loops


The Read method of the CsvParser instance returns an array of strings after splitting the input line accordingly to your delimiter. At this point you just need to reference the first element of the array without any loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download