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?

You are creating a random number between 0 and 20, then are loading an unknown number of lines in. This can be more or less than 20. ie If you try to access the 16th line of a file with only 13 lines, it will be outside of the bounds of the array.

Try creating the random number after the file is loaded:

string [] arrLines = strAllFile.Split('\n');
rand = r.next(0, arrLines.Length - 1);
answer = arrLines[rand];

When I try that I get the error message: "System.Random does not contain a definition for 'next' and does not contain an extension method 'next' accepting a first argument of type 'System.Random' could be found (are you missing a using directive or an assembly reference)". Any ideas on how to fix this?

What is your class name which you have defined?

try this code

StreamReader reader = new StreamReader("Answers.txt");
                    string strAllFile = reader.ReadToEnd().Replace("\r\n", "\n").Replace("\n\r",
                    "\n");
                    string[] arrLines = strAllFile.Split('\n');
                    rand = r.Next(0, arrLines.Length - 1); //rand is a predefined variable
                    Console.WriteLine(rand + "---");
                    answer = reader.ReadLine();
                    answer = arrLines[rand];
                    Console.WriteLine(answer + "******");
                    reader.Close();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.