2

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--|
  • 1
    What are these lines? We need a [mcve]. Is one of the lines by chance, empty? –  Aug 22 '19 at 20:42
  • 3
    The first line has to be empty. At least I can't think of any other reason. – div Aug 22 '19 at 20:44
  • 3
    Actually _any_ line being empty will trigger the error. – D Stanley Aug 22 '19 at 20:46
  • 2
    There are empty lines in the text you just added. Use the debugger to identify these things. `linesRead[i]` has a value, and you can set a breakpoint in the code and use the watch window to find out what that value is. A few people figured out that at some point, it's an empty string. Lo and behold: Some of your lines are empty. – 15ee8f99-57ff-4f92-890c-b56153 Aug 22 '19 at 20:46

4 Answers4

3

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

Try

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

instead.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
2

I would null/empty check each line, just in case.

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

foreach (var line in linesRead)
{
    if (!string.IsNullOrEmpty(line) && line[0] == '5')
    {
        //Do stuff
    }
}
Tom Faltesek
  • 2,768
  • 1
  • 19
  • 30
1

It means that you have an empty line somewhere in your file.

You can skip those lines with:

if (linesRead[i].Length > 0 && linesRead[i][0] == '5')
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44
1

In the case that you have an empty string, the character linesRead[i][0] is '\0' (that's used to mark the end of a string).

If you change your line 5 to if(linesRead[i].Length > 0 && linesRead[i][0] == '5')) then you could skip the empty string cases.

Royce Yang
  • 43
  • 5