I created a .txt file with 20 lines of text. I need to read a random line. This code works for the most part:
Random r = new Random();
rand = r.Next(0,20); //rand is a predefined variable
StreamReader reader = new StreamReader("Answers.txt");
answer = reader.ReadLine();
string strAllFile = reader.ReadToEnd().Replace("\r\n", "\n").Replace("\n\r",
"\n");
string[] arrLines = strAllFile.Split(new char[] { '\n' });
answer = arrLines[rand];
reader.Close();
Everything works except for occasionally I will get an error that "The index is outsides the bound of the array." Every other part of the code works. Can anyone find the issue? I believe it is that the "arrLines" max index is less than 20 and so if the random value is over "arrLines" max I could get this error. If this is true, how would I fix this?