C#从嵌入的文本文件中选择随机行?

时间:2013-05-13 16:01:52

标签: c# visual-studio

如何从嵌入的文本文件中选择随机行?

当我运行该程序时,它崩溃并给我这个错误(路径中的非法字符)在这一行(String [] randFirst = File.ReadAllLines(Separis_Fantasy_Tools_PE.Properties.Resources.fnames);)

这就是我所拥有的。

private void btnRandom_Click(object sender, EventArgs e)
    {
        String nFirstName;
        String nLastName;

        Random fname = new Random();
        Random lname = new Random();


            String[] randFirst = File.ReadAllLines(Separis_Fantasy_Tools_PE.Properties.Resources.fnames);
            nFirstName = randFirst[fname.Next(randFirst.Length)];

            String[] randLast = File.ReadAllLines(Separis_Fantasy_Tools_PE.Properties.Resources.lnames);
            nLastName = randLast[lname.Next(randLast.Length)];


        txtCharacterName.Text = nFirstName + " " + nLastName;
        return;


    }

1 个答案:

答案 0 :(得分:1)

Separis_Fantasy_Tools_PE.Properties.Resources.fnames是文本文件本身,而不是文本文件的路径。

private void btnRandom_Click(object sender, EventArgs e)
{
    String nFirstName;
    String nLastName;

    Random rnd= new Random();


    String[] randFirst = Separis_Fantasy_Tools_PE.Properties.Resources.fnames.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
    nFirstName = randFirst[rnd.Next(randFirst.Length)];

    String[] randLast = Separis_Fantasy_Tools_PE.Properties.Resources.lnames.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
    nLastName = randLast[rnd.Next(randLast.Length)];


    txtCharacterName.Text = nFirstName + " " + nLastName;
    return;


}

另一个变化是,您不需要两个随机对象,只需使用一个,然后两次调用next。您可能不需要担心它,但您也应该意识到编写代码的方式可能会得到same random number every time you call your function(如果你真的很快)。