Agnieszka Polec
Agnieszka Polec

Reputation: 1501

how to use csvHelper to read the second line in a csv file

I have a csv file with two lines, the first one is the header line, which includes 36 columns separated by ,

The second line is the values, which are 36 value separated by ,

I want to read the second line, I found that all people talk about csvHelper package, so I download it, but it doesn't have any dll to add to my project.

my question is how to include it and how to read the second line.

I know that I can install it using Install-Package CsvHelper but I don't want that way because I want to deploy this application on a server. Thus, I would prefer If there is a way like add reference or something.

if i knew how to include it, reading the second line wouldn't be hard. I would do something like this:

  1. load the csv file
  2. read the first line and ignore it.
  3. read the second line and split it by ,.

Upvotes: 11

Views: 20940

Answers (2)

Hakan Fıstık
Hakan Fıstık

Reputation: 19421

The accepted answer is a workaround for the problem, but the library has the first-class solution for this common case
CsvConfiguration class has a property HasHeaderRecord which could be set to true, this will cause the library to skip the first line in the file.

CsvConfiguration configuration = new CsvConfiguration { HasHeaderRecord = true };

using (TextReader sr = new StringReader(fileContent))
{
    CsvReader reader = new CsvReader(sr, configuration);
}

here is a snippet of the Documentation

Gets or sets a value indicating if the CSV file has a header record. Default is true.

UPDATE in the newer version of the library the class CsvConfiguration is just renamed to Configuration

Upvotes: 14

Tim Schmelter
Tim Schmelter

Reputation: 460058

You could use TextReader.ReadLine() to skip the first line:

using (TextReader reader = File.OpenText("filename"))
{
    reader.ReadLine();
    // now initialize the CsvReader
    var parser = new CsvReader( reader ); // ...
}

Upvotes: 22

Related Questions