Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm making a quiz where the user can put his questions and answers. That's going into a text file. I don't know how to take part of text(whole line, it doesn't matter if it's first or last line in text). I want to take random questions from that text file so I thought there is way to take serial number of line and call it to get question. I want then use

Random r = new Random();
who will choose random number(question)

This is part of code who shows writing question into text file.

StreamWriter sw = new
StreamWriter(loc,true);
sw.WriteLine(textBox1.Text);
sw.Close();
For example Random r = new Random(); choose number 5 and then it will get 5th line in text (5th question) and put it into label. I hope you understood what I want to do

What I have tried:

I don't know what to do,I tried to find command for that but I didn't found it.
Posted
Updated 27-Oct-17 2:02am

You have to read line by line from the beginning of the file, until you reach the line you want.
It would be more efficient (if there aren't too many lines) to read all the lines at once in memory (e.g. in a List<string>) and get the lines from there:
C#
List<string> allQuestions = File.ReadAllLines(fileName).ToList();

For example, to get a random question:
C#
string question = allQuestions[r.Next(allQuestions.Count - 1)];

(F-ES Sitecore told you here about the random numbers.)

The next (easy) step would be to include the answers as well...
 
Share this answer
 
Comments
Member 13489042 28-Oct-17 7:25am    
I get error " 'System.Array' does not contain a definicion for 'ToList' ".
I added Sytem.Data.Linq but it doesn' working.
I have visual studio 2005 :(
[no name] 28-Oct-17 12:26pm    
File.ReadAllLines(fileName).ToList(); requires .Net 4.

You have to use something like:

List<string> allQuestions = new List<string>();
string[] readLines = File.ReadAllLines(fileName);
allQuestions.AddRange(readLines);

or, you don't have to use a list at all:

string[] allQuestions = File.ReadAllLines(fileName);
string question = allQuestions[r.Next(allQuestions.Length - 1)];
If you look at the documentation for Random you'll see you can call it like this

r.Next(3)


or

r.Next(1, 3)


The first will choose a random number between 0 and 3 exclusive (ie 2), the second from 1 and 2. So the first will choose 0, 1 or 2 and the second 1 or 2. So you need to know the maximum number of questions and use one of those versions of Next to get a random number in the range of questions you have.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900