Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

csv

csvhelper

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 ,.
like image 437
Agnieszka Polec Avatar asked Jul 29 '14 11:07

Agnieszka Polec


2 Answers

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 ); // ...
}
like image 165
Tim Schmelter Avatar answered Oct 20 '22 21:10

Tim Schmelter


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

like image 39
Hakan Fıstık Avatar answered Oct 20 '22 20:10

Hakan Fıstık