私は c# (winforms) で何かをしようとしていますが、小さな問題で立ち往生しています。この問題に関連するすべてのコードを試しましたが、成功しませんでした。答える前に問題を読んでください。
私には2つの機能があります。特定の .txt ファイルからランダムな行を取得し、それを別のファイルに入れる関数を 1 つ作成したいと考えています。
その例を次に示します。
//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ファイルからランダムな名前が必要です。ここに簡単な説明付きの小さな写真があります。