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

◇◆丶佛笑我妖孽 提交于 2019-12-22 20:18:41

问题


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


回答1:


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



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



回答3:


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


来源:https://stackoverflow.com/questions/5796224/c-sharp-sharp-reading-random-line-from-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!