-4

How do you pick a random line from an embedded text file?

When I run the program it crashes and gives me this error (Illegal characters in path) On this line ( String[] randFirst = File.ReadAllLines(Separis_Fantasy_Tools_PE.Properties.Resources.fnames); )

This is what I have.

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;


    }
cpar
  • 21
  • 2
  • 7
    What is not working about it? Is it throwing an error? Is it giving bad output? – DotNetRussell May 13 '13 at 16:02
  • When I run the program it crashes and gives me this error (Illegal characters in path) On this line ( String[] randFirst = File.ReadAllLines(Separis_Fantasy_Tools_PE.Properties.Resources.fnames); ) – cpar May 13 '13 at 16:05
  • That might be something you would want to add to your question.... Big difference between it not outputting right and exploding.. – DotNetRussell May 13 '13 at 16:06
  • You can use one Random generator, too. Maybe give us some information about the Path used to load the files? – Patrick Magee May 13 '13 at 16:27

1 Answers1

1

Separis_Fantasy_Tools_PE.Properties.Resources.fnames is the text file itself, not a path to the text file.

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;


}

One other change, you don't need two random objects, just use one and call next twice. You likely don't need worry about it but you should also be aware that the way you wrote your code you could potentially get the same random number every time you call your function (if you do it really fast).

Community
  • 1
  • 1
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431