我正在使用WinForms。在我的" C:\ image \ SourcePath_Folder"目录我有多个子文件夹。我想将每个文件夹中的3个文件随机复制到另一个名称相同的目录中。
这是我到目前为止所拥有的。这会将子目录中的所有文件复制到另一个目录。代码不会从每个子文件夹中随机挑选出文件。如何首先选择随机文件,如何将其限制为仅3个文件?
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);
}
}
答案 0 :(得分:1)
作为一个小命令行版本应该很容易使用...
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);
}
}
使用:
using System;
using System.IO;
using System.Linq;