Search code examples
c#asp.netfilefile-iodirectory

Select random file from folder


My folder contain more then 100 zip files. I want to select random 6 zip file from a folder.

I try:

DirectoryInfo test = new DirectoryInfo(@ "C:\test").GetFiles();
foreach(FileInfo file in test.GetFiles()) {

  Random R = new Random(); //try to apply random logic but fail.

  if (file.Extension == ".zip") {
    string a = "";
    for (int ListTemplate = 0; ListTemplate < 6; ListTemplate++) {
      a += file.FullName; //Want to choose random 6 files.
    }

  }
}            

Is there any way to do this.


Solution

  • To do this, you want to randomize the order in which the files are being sorted.

    Using the sort shown in this answer (you can use the more cryptographic approach as well if you want)

    var rnd = new System.Random();
    var files = Directory.GetFiles(pathToDirectory, "*.zip")
                         .OrderBy(x => rnd.Next())
                         .Take(numOfFilesThatYouWant);
    

    You can then evaluate files in your foreach. It should give the number of files that you want to process, in a random order.