5

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.

ssuperczynski
  • 3,190
  • 3
  • 44
  • 61
Kushagra Kasbi
  • 135
  • 2
  • 9

2 Answers2

4

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);
        }
    }
James John McGuire 'Jahmic'
  • 11,728
  • 11
  • 67
  • 78
1

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/

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
Josh Close
  • 22,935
  • 13
  • 92
  • 140