2016-08-23 3 views
0

私はWinFormsを使用しています。私の "C:\ image \ SourcePath_Folder"ディレクトリには、複数のサブフォルダがあります。私はランダムに同じ名前の別のディレクトリに各フォルダから3つのファイルをコピーしたい。すべてのサブディレクトリからランダムに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); 
     } 
    } 

enter image description here

+0

あなたが立ち往生しているどの部分、正確に? –

+0

各サブフォルダからランダムに3つのファイルをコピーします。それらを別のフォルダ/ディレクトリに入れます。 @ rory.ap – taji01

+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); 
    } 
} 

ところでusings:

using System; 
using System.IO; 
using System.Linq; 
+0

'each'サブフォルダから3つのランダムファイルを探していました – taji01

+1

このコードは' @ "C:\ image \ SourcePath_Folder \" '包括的サブフォルダランダムに3つのファイルを選択してコピーします。 'int count = 3'、結果は' FileInfo [] randomFiles'に3つのエントリがあります – MaxKlaxx

+0

ありがとうございました:) – taji01

関連する問題