Search code examples
c#arraysindexoutofrangeexception

Can't find the reason of "IndexOutOfRangeException"


I'm getting a weird issue with indexOutOfBounds exception. I need to read the first character of each string in the array.

I get an exception in 5th line (linesRead[i][0]). Weirdest part for me is that when I tried to add lines for debugging Console.WriteLine(linesRead[0][0]) / Console.WriteLine(linesRead[linesRead.Length-1][0]) it works just fine.

string[] linesRead = System.IO.File.ReadAllLines(@"test.txt"); //Just a bunch of lines

for (int i = 0; i < linesRead.Length; i++)
{
    if (linesRead[i][0] == '5')
    {
        //Do stuff
    }
}

The text inside of test.txt:
5|f-----g-----c---g-----a---|

6|--c-----------------------|
5|---Aa-f-----g-----c-------|

5|------ccdf-ff-----g-----c-|

6|--------------c-----------|
5|--g-----a------Aa-f-----g-|

5|----c-------------ccdf-f--|

Solution

  • if (linesRead[i][0] == '5') will trigger this error if a line is empty.

    Try

    if (linesRead[i].StartsWith("5"))
    

    instead.