2

I have written a small program to read data from a csv file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace test
{
    class Program
    {
        static void Main( string[] args )
        {    
            var reader = new StreamReader( File.OpenRead( @"C:\Users\Desktop\Results.csv" ) );

            List<string> listA = new List<string>();
            List<string> listB = new List<string>();

            while ( !reader.EndOfStream )
            {
                var line   = reader.ReadLine();
                var values = line.Split( ',' );

                listA.Add( values[0] );
                listB.Add( values[1] );
            }

            // Print column one.
            Console.WriteLine( "Column 1:" );
            foreach ( var element in listA )
                Console.WriteLine( element );

            // Print column two.
            Console.WriteLine( "Column 2:" );
            foreach ( var element in listB )
                Console.WriteLine( element );

            Console.ReadKey();
        }
    }
}

I get the following error message on line listB.Add( values[1] );

Index was outside the bounds of the array.

When I comment out everything to do with listB, it works and shows me the 1st column...

Could someone please help me understand what I am doing wrong?

Thank you,

leppie
  • 115,091
  • 17
  • 196
  • 297

4 Answers4

1

This error probably occurs because a line was read that doesnt have a "," char or text behind it. Therefore values[1] does not exist and the error gets thrown. You can check for that case for example with

if(values.length < 2)
{
    //do what ever is needed in your case
}

or you make sure that the file that you are reading has at least 2 values seperated by a "," on every line. A line like

text1,

would cause that error for example.

T_D
  • 1,688
  • 1
  • 17
  • 28
1

That's because your this line line.Split( ',' ); must be returning, a single item. Your returned array values has only one element.

You should check if any element is present before adding, something like this:-

if(values.Length > 1)
    listB.Add( values[1] );
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
0

On the one of the line in your file/document you don't have any spliting. I mean you don't have

value,value

You can make check if the string array contain two values and after that perform adding to the list or just fix your file.

Also you can try to see how to read csv file with OleDbConnection.

In this question I wrote how to read and store data in DataTable: C# Read a particular value from CSV file

Community
  • 1
  • 1
mybirthname
  • 17,949
  • 3
  • 31
  • 55
0

Enumerate through your csv data like this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CSV_ReadCsvColumn
{
    class Program
    {
        private static IEnumerable<string[]> LoadCsvData(string path, params char[] separator)
        {
            return from line in File.ReadLines(path)
                   let parts = (from p in line.Split(separator, StringSplitOptions.RemoveEmptyEntries) select p)
                   select parts.ToArray();
        }

        static void Main()
        {
            IEnumerable<string[]> lines = LoadCsvData(@"file.csv", ';');

            if (lines != null)
            {
                // Print column one.
                foreach (var line in lines)
                    Console.WriteLine(line[0]);

                // Print column two.
                foreach (var line in lines)
                    Console.WriteLine(line[1]);
            }
        }
    }
}
MrMAG
  • 1,194
  • 1
  • 11
  • 34