开发者

C# (sharp) reading random line from txt file [duplicate]

This question already has answers here: 开发者_运维百科 Read random line from a file? c# (2 answers) Closed 9 years ago.

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


var lines = File.ReadAllLines(path);
var r = new Random();
var randomLineNumber = r.Next(0, lines.Length - 1);
var line = lines[randomLineNumber];


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)]);


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++;
            }
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜