从txt文件中读取随机行的C#(sharp)
var lines = File.ReadAllLines(path);
var r = new Random();
var randomLineNumber = r.Next(0, lines.Length - 1);
var line = lines[randomLineNumber];
最简单的解决方案是将读取所有的行存储器和选择一个随机。假设所有的行都可以放入内存中。
string[] allLines = File.ReadAllLines(path);
Random rnd1 = new Random();
Console.WriteLine(allLines[rnd1.Next(allLines.Length)]);
阵列没有计数属性... – 2011-04-26 20:51:23
感谢马克。我的坏,纠正它。 – rkg 2011-04-26 20:54:36
这是行不通的......你错过了你实际从行数组中获取行的部分。另外,马克说。 – 2011-04-26 20:55:02
下面是一个代码示例:
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++;
}
}
现在,为什么你会为了获得计数而将所有行读入内存,然后重新读取文件以获得所需的行?您只需“ReadAllLines”,然后从数组中进行选择。 – 2011-04-26 22:02:59
http://stackoverflow.com/questions/3745934/read-random-line-from-a-file-c/3745973#3745973将工作与任何大小的文件,并不需要你读取整个文件到内存中。 – 2011-04-26 22:00:16