Reputation: 155
So this is the code I am using currently, but I don't specifically want to create my own reader. My problem is that I want to read a full csv file line by line, but the file contents will change from time to time, so it has to be generic.
This is what I am using currently,
try
{
var Lines = File.ReadAllLines(path);
var csvRawData = from line in Lines select (line.Split(',')).ToArray();
var csvData = csvRawData.ToList();
return csvData;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Logger.Log(ex.Message, true);
return null;
}
The return csvData is of type List. I then just separate the content out from it manually.
Upvotes: 5
Views: 12502
Reputation: 23403
You say CsvHelper
, but from your code it doesn't look like you're actually using it. If you are using it, you can use the GetField
methods to pull a field by header name of index. Take a look at the documentation for more information on how to use it.
https://joshclose.github.io/CsvHelper/examples/reading/
Upvotes: 1
Reputation: 12684
Here is an example of reading line by line, where the second line has a different 'type' then the first line:
using (StreamReader reader = new StreamReader(filePath))
{
using (CsvReader csv = new CsvReader(reader))
{
csv.Read();
Type1 sample = new Type1();
sample.Id = csv.GetField<int>(0);
sample.Lines = csv.GetField<int>(1);
csv.Read();
Type2 sample2 = new Type2();
sample2.Angle = csv.GetField<double>(0);
sample2.Distance = csv.GetField<int>(1);
}
}
Upvotes: 4