Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accessing FieldHeader after GetRecords() causes exception #495

Closed
j-hudecek opened this issue Mar 15, 2016 · 2 comments
Closed

Accessing FieldHeader after GetRecords() causes exception #495

j-hudecek opened this issue Mar 15, 2016 · 2 comments

Comments

@j-hudecek
Copy link

I have this code

 var csv = new CsvReader(new StreamReader(filename));
 var data = csv.GetRecords<string[]>();
 var header = csv.FieldHeaders;

and I get an exception "You must call read on the reader before accessing its data. ". GetRecords docs say "Read method should not be used when using this."

@nebenjamin
Copy link

Having just dealt with a similar issue (#131), the issue is that GetRecords returns an IEnumerable constructed using the yield keyword. GetRecords calls Read as you iterate over the IEnumerable. Since you haven't iterated over the collection, Read hasn't been called.

The following should resolve the issue:

var csv = new CsvReader(new StreamReader(filename));
var data = csv.GetRecords<string[]>().ToList();
var header = csv.FieldHeaders;

It does seem like this is a common enough issue that the CsvReader's constructor may need to be populating the FieldHeaders property instead. IMHO, for most people attempting to get FieldHeaders, the value of doing so is to check for the presence of specific headers before reading data from the file. I'm assuming that there was a reason for writing it this way, and I'm curious to know what the reason is.

@JoshClose
Copy link
Owner

In 3.0, Read and ReadHeader are separate. This would allow you do to this.

csv.Read();
csv.ReadHeader();
var header = csv.FieldHeaders;
var records = csv.GetRecords<MyType>();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants