I'm attempting to create a randomly generated string of words, which works fine unless I call it multiple times in a row. This is on a WebForms page that and the list of words comes from a file.
I suspect I'm not understanding something with out C# or possibly ASP.NET works in this case, can someone explain why this is happening and how to approach a fix?
Here is the method
public string GeneratePhrase()
{
// get dictionary file
var data = File.ReadAllLines(HttpContext.Current.Server.MapPath("~/libs/words.txt"));
Random rand = new Random();
int r1 = rand.Next(data.Count());
int r2 = rand.Next(data.Count());
int r3 = rand.Next(data.Count());
string p1 = data.ElementAt(r1).ToLower();
string p2 = data.ElementAt(r2).ToLower();
string p3 = data.ElementAt(r3).ToLower();
string ret = string.Format("{0}{1}{2}", p1, p2, p3);
return ret;
}
If I call this once during a PostBack
, it's fine and always creates a random combination of words. However if I use this more than once during a PostBack, it simply repeats the same random string from each call.
string s1 = this.GeneratePhrase();
string s2 = this.GeneratePhrase();
string s3 = this.GeneratePhrase();
Response.Write(s1);
Response.Write(s2);
Response.Write(s3);
output
tirefriendhotdog
tirefriendhotdog
tirefriendhotdog
Any reason on why this may happen?