4

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.

4b0
  • 21,981
  • 30
  • 95
  • 142
  • possible duplicate of [select random file from directory](http://stackoverflow.com/questions/742685/select-random-file-from-directory) – Stasel Jun 09 '14 at 06:27
  • you don't use the random anywhere, just pick a random number between 0 and `GetFiles().Count - 1`... (no need for the foreach) – Sayse Jun 09 '14 at 06:27
  • I search and found that link but it select all files.Not duplicate. – 4b0 Jun 09 '14 at 06:28

1 Answers1

2

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.

Community
  • 1
  • 1
Yaakov Ellis
  • 40,752
  • 27
  • 129
  • 174
  • You could remove the `.where` via using the extension version of [`GetFiles("*.zip")`](http://msdn.microsoft.com/en-us/library/8he88b63(v=vs.110).aspx) – Sayse Jun 09 '14 at 06:42
  • Also, to create a string `a` with all the file names, use `string.Join`, not a loop, for example `string a = string.Join("\r\n", files.Select(x => x.FullName));`. – Jeppe Stig Nielsen Jun 09 '14 at 07:25