C# 如何使用C从.txt文件中获取随机单词?

C# 如何使用C从.txt文件中获取随机单词?,c#,C#,如您所见,我决定创建一个包含.txt文件中所有文本的内容字符串。现在如何从该字符串中选择一个非数组的随机字?您应该在空格上拆分,然后使用random获得一个随机整数 private async void Button_Click(object sender, RoutedEventArgs e) { int word = 1; string FileName; openFileDialog1.Filter = "txt files

如您所见,我决定创建一个包含.txt文件中所有文本的内容字符串。现在如何从该字符串中选择一个非数组的随机字?

您应该在空格上拆分,然后使用random获得一个随机整数

private async void Button_Click(object sender, RoutedEventArgs e)
    {
        int word = 1;
        string FileName;
        openFileDialog1.Filter = "txt files (*.txt)|*.txt";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.InitialDirectory = @"C:\";
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.ShowDialog();
        FileName = openFileDialog1.FileName;
        FileStream stream = File.Open(FileName, FileMode.Open);
        await Task.Run(() =>
        {
            using (StreamReader reader = new StreamReader(FileName))
            {
                string content = reader.ReadToEnd();
            }
        });
    }

我认为这取决于文件的大小。。。若它不是大的,你们可以在内存中用空格分割,然后使用随机索引从结果列表中得到一个单词。如果文件可能非常大,这种方法可能不可接受,因此您可能需要在文件的随机位置直接访问,并查找该位置后的第一个单词。您的异步IO操作不正确。你不需要Task.Run。我的问题不完全是关于异步的,但为什么我错了?即使你的问题不是关于异步的,你仍然应该解决这个问题。1它会让你的代码变得更好,2个人也不会因此打扰你
Random random = new Random();
string[] split = content.Split(" ");
string randomString = split[random.Next(0,split.length)];