c# - 显示 .txt 文件中的随机行 - C#

标签 c# winforms

我正在尝试用 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 文件中的随机名称显示在文本框中,方法是右键单击文本框并选择加载我的函数的项目。这是一张带有简单说明的小图片。

enter image description here

最佳答案

就像 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/

相关文章:

c# - 如何在 C# 中将 DLLImport 与结构作为参数一起使用?

c# - DataGridViewComboBox - 如何允许任何值?

c# - 获取/设置 RichTextBox 的第一个可见行

c# - Winform TextBox无法显示文字

c# - System.Net.HttpWebRequest.GetResponse() 错误 "ResponceSystem.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel"

c# - 异常后代码如何执行?

c# - 父节点内列表的序列化(集合扁平化)

c# - 为什么 AddMvc 需要 Action<MvcOptions> 而不是 MvcOptions?

.net - 将表单的一个实例的 TextBox 控件的更改值更新到所有实例

c# - Windows 窗体帮助按钮更改光标