Burak Burak - 4 years ago 129
C# Question

Streamreader and "Index was outside the bounds of the array" error [solved]

I didn't write any array length but when i try to read .csv file i get the "Index was outside the bounds of the array" error. .csv file is about 1 000 000 line. Is there anyone to fix this code?

.csv file lines are like below.


0000000,26.0000000000000,38.0000000000000,30.01.2017,0,0,0,,,0,0,,0,,0,0,0,0


string[] read;
char[] seperators = { ',' };


try
{
Image img = Image.FromFile(txtFilePath.Text);
Graphics g = Graphics.FromImage(img);
pictureBox1.Image = img;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

StreamReader sr = new StreamReader(txtFile2Path.Text);

string data;

while ((data=sr.ReadLine()) !=null)
{
read = data.Split(seperators, StringSplitOptions.None);

float x = float.Parse(read[1]);
float y = float.Parse(read[2]);
string z = read[10];
}
}


catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Ben Ben
Answer Source

Just to clarify the answer for anyone that ends up here..

        while ((data=sr.ReadLine()) !=null)
        {
            read = data.Split(seperators, StringSplitOptions.None);
            if (read.Length >= 11)
            {
                float x = float.Parse(read[1]);
                float y = float.Parse(read[2]);
                string z = read[10];
            }
        }

When accessing an array that may not be the desired length, check it first.

An Index was outside the bounds of the array exception will only be thrown when a line of code is trying to access an item (N-1) in the array that does not exist - due to the array having less than (N) items

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download