Home > front end >  How to read individual columns from CSV file?
How to read individual columns from CSV file?

Time:01-26

Suppose the following is my CSV file:

Step,Magnetization,Energy
1,0.009375,12
2,0.009375,12
3,0.009375,12
4,0.009375,12
5,0.009375,12

I want to read the file and create three separate lists or arrays.

So, I wrote the following code:

class Program
{
    static void Main(string[] args)
    {
        string csvFilePath = @"ising.csv";

        CsvConfiguration myConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
        {
            Delimiter = ","
        };

        using (var reader = new StreamReader(csvFilePath))
        using (var csv = new CsvReader(reader, myConfig))
        {
            List<double> xAxisForSteps = new List<double>();
            List<double> yAxisForMagnetization = new List<double>();
            List<double> yAxisForEnergy = new List<double>();

            while (csv.Read())
            {
                int step = csv.GetField<int>("Step");
                double magnetization = csv.GetField<double>("Magnetization");
                int energy = csv.GetField<int>("Energy");

                xAxisForSteps.Add(step);
                yAxisForMagnetization.Add(magnetization);
                yAxisForEnergy.Add(energy);
            }
        }
    }
}

This gives the following error:

An unhandled exception of type 'CsvHelper.ReaderException' occurred in CsvHelper.dll

Additional information: The header has not been read. 
You must call ReadHeader() before any fields can be retrieved by name.

IReader state:

   ColumnCount: 0    
   CurrentIndex: -1    
   HeaderRecord:    

IParser state:

   ByteCount: 0    
   CharCount: 27    
   Row: 1    
   RawRow: 1    
   Count: 3    
   RawRecord:

Step,Magnetization,Energy

How to resolve it?

EDIT:

After calling csv.ReadHeader() I get the following error:

An unhandled exception of type 'CsvHelper.ReaderException' occurred in CsvHelper.dll

Additional information: No header record was found.

IReader state:

   ColumnCount: 0    
   CurrentIndex: -1    
   HeaderRecord:  

IParser state:

   ByteCount: 0    
   CharCount: 0    
   Row: 0    
   RawRow: 0    
   Count: 0

   RawRecord:

CodePudding user response:

Try changing your code like this:

List<double> yAxisForEnergy = new List<double>();

if(csv.Read() && csv.ReadHeader()){
    while (csv.Read())

I'm not sure I agree that is the most obvious design, but that is how it should be done according to the documentation.

Please note that this will depend on the currentCulture, since not all cultures use . as decimal separator. Consider specifying the invariantCulture.

  • Related