0

I am getting the error "Index was outside the bounds of the array."

This is what I want to have :

  • check if the log line contain "ERROR" then check if the bottom line contain " at "
  • if true check if the bottom line contain " at "
  • While the state is true increment the string variable called checkDescr with the line
  • do this again and again until the state is false.

Here is my code :

foreach (string log in logs)
{
    if (log.Contains("ERROR"))
    {

        nextLine = index + 1;
        descriptionLine = index + 2;

        string checkDescr = "";
        int descNb = descriptionLine + 1;
        checkDescr = logs[descNb];

        if (checkDescr.Contains(" at "))
        {

            while (logs[descNb].Contains(" at "))
            {
                descNb++;
                checkDescr = checkDescr + logs[descNb];

            }

        }
    }
}
Dominique
  • 16,450
  • 15
  • 56
  • 112
feperc
  • 9
  • 1
  • 2
    What if _all_ lines contain " at " ? – Fildor Jul 05 '22 at 13:23
  • What if "ERROR" appears in the last ( or second to last ) line? – Fildor Jul 05 '22 at 13:24
  • ^^ You need to add boundary checks. And learn how to use a debugger. If you get that error one of your index vars moves beyond an array boundary. You need to find out where, then fix it. – Fildor Jul 05 '22 at 13:25
  • 1
    well, you could for instance check if `descNb < logs.Length` before you try to access `logs[descNb]` – derpirscher Jul 05 '22 at 13:27
  • BTW: Auto-Examining Logs is easier if you log to a DB, where you'd probably could filter for ERROR and have a dedicated column for the stacktrace. – Fildor Jul 05 '22 at 13:30
  • Thanks, I started c# a few weeks ago I'm still learning. I have to extract some lines from a .log file as you already understand. I first check if the line contain "ERROR" if so I take it and write it inside a .csv file and i want to write in the same line the line bottom lines that start with " at ". It's a log file so there is no risk that all lines contains " at " and if they all contains "ERROR" I have to extract all and write it in my csv file. – feperc Jul 05 '22 at 13:37
  • Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Yong Shun Jul 05 '22 at 13:52

1 Answers1

0

Just replace:

while (logs[descNb].Contains(" at "))

... by:

while ((logs.Length < descNb) && (logs[descNb].Contains(" at ")))

Keep out: there's a catch: in case logs.Length == descNb, then logs[descNb] generates the IndexOutOfRangeException, but the C# compiler stops the while-condition when the first condition is not met. In case you're dealing with an older compiler, you might still encounter a problem (but it's very unlikely).

Dominique
  • 16,450
  • 15
  • 56
  • 112