READER.FILL method without ReadHeaderRecord issue

Sep 15, 2012 at 10:53 PM

Hi Kent,

first of all thank you for this cool library.

I'm very new in using it and I need to parse  a CSV file into a datatable. Example provided in CHM is clear but it works fine when CSV has a valid HeaderRecord.

If it's not valid or reader.ReadHeaderRecord() is not called, it throws this exception:

"No header record has been set for this CsvReader."

Another user had the same problem but he resolved creating a custom HeaderRecord (I have no idea how to accomplish this)

So I ask:

1. If this is a bug, will you fix it?

2. If not, how to teach reader to auto-create columns of type "column_1,column_2" etc.? (can you provide a step by step on how implement a HeaderRecord from code?)

Thank you

 

 

 

 

Coordinator
Sep 20, 2012 at 1:21 PM

Hi gersis,

You can provide your own HeaderRecord as follows:

 

using (var reader = CsvReader.FromCsvString("foo,bar"))
{
    reader.HeaderRecord = new HeaderRecord(new string[] { "column_1", "column_2" });
    var dataset = new DataSet();
    reader.Fill(dataset);
}

 

You cannot dynamically allocate column names as they are "discovered" in the data set. However, you can always define a maximum number of columns that would ever be required. eg:

using (var reader = CsvReader.FromCsvString("foo,bar"))
{
    var columnNames = from i in Enumerable.Range(0, 100)
                      select "column_" + i;
    reader.HeaderRecord = new HeaderRecord(columnNames);
    var dataset = new DataSet();
    reader.Fill(dataset);
}

Hope this helps,
Kent

Sep 21, 2012 at 8:39 AM

It worked for me. Thank you!