0

My Question is Random File will not repeat ,When I Click Rendom File will show "1:. Again I am Click Rendom File will show "2" But In Case show 1,1

Random rand = new Random();
string[] filess = Directory.GetFiles("Select Directory");
string randomFile = filess[rand.Next(filess.Length)];

I want How to Stop Repeat File Once will show 1, Next it never show 1

Kit
  • 20,354
  • 4
  • 60
  • 103
  • Does this answer your question? [How can i generate random numbers without repeating/duplicate the same number?](https://stackoverflow.com/questions/46882688/how-can-i-generate-random-numbers-without-repeating-duplicate-the-same-number) – Dour High Arch Jul 25 '21 at 18:03

1 Answers1

0

The .NET Random class does not generate pure random numbers. The default behavior seeds with the current time which may not change as often as you run the your code, and hence the duplicate values.

To fix this, the Random class constructor has a overload that takes a seed. Pass on a different number every time you initialize the Random class.

Random ran = new Random(GetRandomSeed());

and write the GetRandomSeed method:

int GetRandomSeed()
{
    byte[] b= new byte[4];
    RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();

    csp.GetBytes(b);
    return BitConverter.ToInt32(b, 0);
}
Kit
  • 20,354
  • 4
  • 60
  • 103
Shameel
  • 632
  • 5
  • 12