0

This is my code, it reads from a text file and places it into the listbox on my form. If there is already something in the text file it works. But if I delete what's in the text file and run the program it crashes and gives me the error "Index was outside the bounds of the array."

at assignment.Request.Name = columns[1]; and I'm not sure why/how to go about fixing it.

public static List<Assignment> GetAssignment()
    {
        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);


        StreamReader textIn =
            new StreamReader(
                new FileStream(path3, FileMode.OpenOrCreate, FileAccess.Read));

        List<Assignment> assignments = new List<Assignment>();

        while (textIn.Peek() != -1)
        {
            string row = textIn.ReadLine();
            string[] columns = row.Split('|');
            Assignment assignment = new Assignment();

            assignment.Employee.Name = columns[0];
            assignment.Request.Name = columns[1];
            assignments.Add(assignment);
        }

        textIn.Close();

        return assignments;
    }
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Alex
  • 155
  • 1
  • 12

2 Answers2

1

You need to make sure that there are at least 2 items in the column array or else it will try to access an array item that doesn't exist:

 while (textIn.Peek() != -1)
        {
            string row = textIn.ReadLine();
            string[] columns = row.Split('|');
            if(columns.length>=2)
            {
            Assignment assignment = new Assignment();

            assignment.Employee.Name = columns[0];
            assignment.Request.Name = columns[1];
            assignments.Add(assignment);
           }
        }
Sean Cox
  • 782
  • 1
  • 5
  • 12
1

PUt condition after reading the file.

if(columns.length >2)
{

 assignment.Employee.Name = columns[0];
            assignment.Request.Name = columns[1];
            assignments.Add(assignment);

}
Hiba
  • 231
  • 1
  • 7
  • 23
  • This wouldn't work. If column length was 1, then you'd still try to access columns[1] which would be out of the range of the array. – Sean Cox Nov 20 '15 at 03:53
  • Check colomn length greater than 2 – Hiba Nov 20 '15 at 03:55
  • I'd also put the line which creates the Assignment instance inside of the condition. It's a waste of memory to create the object if it is never used. It would be greater or equal to 2, not greater than 2. – Sean Cox Nov 20 '15 at 03:55
  • Create if there is some element in column. – Hiba Nov 20 '15 at 03:57