我正在尝试用 c# (winforms) 做一些事情,但我遇到了一个小问题。我已经尝试了与此问题相关的所有代码,但没有成功。请在回答之前阅读问题。
我有两个功能。我想创建 1 个函数,该函数将从特定的 .txt 文件中获取随机行并将其放入另一个文件中。
这是一个例子:
//This is a ContexMenuStrip, a right click menu item that need to load Function1 (check the picture below
private void pdkName_Click(object sender, EventArgs e)
{
Function1();
}
private void Function1()
{
//CODE to Count and Display random line from .txt file
}
到目前为止,我已经尝试了许多之前在 stackoverflow.com 上发布的代码,并且我也尝试了与它们的大量组合。我将其中一些粘贴在这里:
Random rand = new Random();
IEnumerable<string> lines = File.ReadLines(@"D:\FirstName.txt");
var lineToRead = rand.Next(1, lines.Count());
var line = lines.Skip(lineToRead - 1).First();
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(@"D:\FirstNames.txt");
while ((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
// Suspend the screen.
System.Console.ReadLine();
//这有效,但仅适用于第一行,不能与它进行任何组合(从其他函数使其随机)
using (StreamReader reader = File.OpenText(@"D:\FirstName.txt")
{
textBox1.Text = reader.ReadLine();
}
var lines = File.ReadAllLines(@"D:\FirstNames.txt");
var r = new Random();
var randomLineNumber = r.Next(0, lines.Length - 1);
var line = lines[randomLineNumber];
string[] lines = File.ReadAllLines(@"D:\FirstNames.txt");
Random rand = new Random();
return lines[rand.Next(lines.Length)];
该函数需要对文件进行计数,选择随机行并将其返回。调用该函数的 ContexMenuStrip 中的项目菜单在 TEXTBOX 上使用。
所以一般来说,我需要 .txt 文件中的随机名称显示在文本框中,方法是右键单击文本框并选择加载我的函数的项目。这是一张带有简单说明的小图片。
最佳答案
就像 fabian 所说的那样,或者在方括号内声明 random 并直接调用 next 方法
string[] lines = File.ReadAllLines(@"C:\...\....\YourFile.txt");
textBox1.Text = lines[new Random().Next(lines.Length)];
关于c# - 显示 .txt 文件中的随机行 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17256537/