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,

4
  • 1
    what is the value of values? Is it being populated with anything? What is the string it should have been populated with? Commented Dec 15, 2014 at 11:34
  • 2
    Step through the code in the debugger and you will most likely quickly find the issue. Commented Dec 15, 2014 at 11:37
  • 2
    No pun intended, Why everyone try to write their own CSV parsers when there are very nice libraries available (e.g joshclose.github.io/CsvHelper)? Commented Dec 15, 2014 at 11:48
  • Excellent snippet, thanks a lot :) Commented Nov 15, 2016 at 11:24

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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] );

Comments

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

Comments

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]);
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.