taji01 taji01 - 3 months ago 16
C# Question

Randomly copy 3 files from all sub-directories

I'm using WinForms. Under my "C:\image\SourcePath_Folder" directory I have multiple sub-folders. I want to randomly copy 3 files from each folder to another directory with the same name.

Here is what I have so far. This copies all the files from the sub directory to another directory. The code doesn't randomly pick out the files from each sub-folder. How do I select the random files in the first place, and how do I limit it to only 3 files?

private void start_btn_Click(object sender, EventArgs e)
{
//Create all of the directories
foreach (string dirPath in Directory.GetDirectories(@"C:\image\SourcePath_Folder\", "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(@"C:\image\SourcePath_Folder\", Destination_txtbox.Text));
}
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(@"C:\image\SourcePath_Folder\", "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(@"C:\image\SourcePath_Folder\", Destination_txtbox.Text), true);
}
}


enter image description here

Answer

as a small command-line version should be easy to use...

static void Main(string[] args)
{
  int count = 3;
  string sourcePath = @"C:\image\SourcePath_Folder\";
  string targetPath = @"C:\bar\";

  Random rnd = new Random();
  FileInfo[] randomFiles = new DirectoryInfo(sourcePath).GetFiles("*.*", SearchOption.AllDirectories)
                              .OrderBy(x => rnd.Next()).Take(count).ToArray();

  foreach (FileInfo file in randomFiles)
  {
    string targetFile = Path.Combine(targetPath, file.Name);
    Console.WriteLine("copy " + file.FullName + " -> " + targetFile);
    file.CopyTo(targetFile);
  }
}

btw the usings:

using System;
using System.IO;
using System.Linq;