blah blah blah is here! blah blah » Close

up2down
link

Hi,

The title says it all. I have a text file with about 50 lines. I only want to display only one line. I've got a random number that chooses the line. I'm new at C# so please keep it simple.

Thanks in advance.

last answered one year ago

2 answers

link

Or you can do it like this:

int i = random; //your random number
string[] lines = File.ReadAllLines(filepath); //make this an instance variable to avoid reading the file over and over again
string randomLine = lines[i];
Console.WriteLine(randomLine);

This seems more better :) never saw the ReadAllLine() nice one.

Thanks a lot.

up1down
link

// i have added the namespace System.IO;
// System.IO.StreamReader
StreamReader sr = new StreamReader("C:\\t.txt");

string line = string.Empty;
Random r = new Random();
// the line count starts at 0
int i = 0;
// set the line we want between 0 and the maximum number
int j = r.Next(0, 2);
/// loop through all the lines skipping nulls.
while ((line = sr.ReadLine()) != null)
{
/// the random number we stored in int j will match and we go the random line.
if (i == j)
{
label1.Text = line;
}
i++;
}

Feedback