3

Can anyone tell me how to read random line from txt file? I want to read random line from txt file and show only that line in textBox. Code examples would be great! Thanx in foward

Mindaugas
  • 31
  • 1
  • 2
  • 3
  • 1
    http://stackoverflow.com/questions/3745934/read-random-line-from-a-file-c/3745973#3745973 Will work with files of any size and doesn't require you to read the entire file into memory. – Jim Mischel Apr 26 '11 at 22:00

3 Answers3

9
var lines = File.ReadAllLines(path);
var r = new Random();
var randomLineNumber = r.Next(0, lines.Length - 1);
var line = lines[randomLineNumber];
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • 1
    Don't allocate a `new Random()` every call, the result will not be random if the calls occur too close together in time. A thread-static `Random` should be used instead. See [Random number generator only generating one random number](https://stackoverflow.com/q/767999). – dbc Dec 31 '18 at 03:10
2

The simplest solution is to read all the lines to memory and pick one randomly. Assuming that all the lines can fit in memory.

string[] allLines = File.ReadAllLines(path);
Random rnd1 = new Random();
Console.WriteLine(allLines[rnd1.Next(allLines.Length)]);
rkg
  • 5,559
  • 8
  • 37
  • 50
1

Here is a code sample:

        int lineCount = File.ReadAllLines(@"C:\file.txt").Length;
        Random rnd = new Random();
        int randomLineNum = rnd.Next(lineCount);
        int indicator = 0;

        using (var reader = File.OpenText(@"C:\file.txt"))
        {
            while (reader.ReadLine() != null)
            {
                if(indicator==randomLineNum)
                {
                    //do your stuff here
                    break;
                }
                indicator++;
            }
        }
Eli Braginskiy
  • 2,867
  • 5
  • 31
  • 46
  • 4
    Now why would you go to the trouble of reading all the lines into memory just to get the count, and then *re-read* the file to get the line you want? You can just `ReadAllLines` and then select from the array. – Jim Mischel Apr 26 '11 at 22:02