ここでの私の目標は次のとおりです。
ユーザーがコンピューター名をコンボボックスに入力する
btn は、コンピューター名を DoWork メソッドに渡す新しいバックグラウンド ワーカー スレッドを開始します。
DoWork メソッドは、定義済みのディレクトリと内容を、入力されたコンピューター名の定義済みの場所にコピーします。
ディレクトリのコピー中。プログレスバーに進行状況を表示したいと思います。backgroundWorker1_ProgressChanged イベントを使用すると、これを行うことができると思います。(WorkReportsProgress プロパティは True に設定されています)
私のコードでは、ディレクトリのサイズを取得するメソッドを追加したことがわかります。これは重要かもしれませんし、そうでないかもしれませんが、とにかくそこに残しました。私の「目標」に関係ない場合は無視してください。また、データをコピーする方法が問題かもしれないと少し感じていますが、本当にわかりません。私はまだこれらすべてに慣れていません。よろしくお願いします。
編集私はこの素晴らしい例をここで見つけました。これは私の質問のほとんどに答えますが、これをバックグラウンドスレッドで正しく実行することにまだ行き詰まっています。これを行うにはバックグラウンドワーカーを使用する必要がありますか?
private void button1_Click(object sender, EventArgs e)
{
//Start background worker thread. Passes computer name the user entered
backgroundWorker1.RunWorkerAsync(comboBox1.Text);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Computer name user entered
string PCName = (string)e.Argument;
string DestinationPath = @"Remote PC C: Drive";
string SourcePath = @"Network share";
//Get File Size
DirectoryInfo dInfo = new DirectoryInfo(SourcePath);
long sizeOfDir = DirectorySize(dInfo, true);
//Use to output. File Size in MB
double size = sizeOfDir / (1024 * 1024);
//Creates Folder on remote PC
Directory.CreateDirectory(DestinationPath);
//Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
}
//Copy all the files
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
{
// Enumerate all the files
long totalSize = dInfo.EnumerateFiles()
.Sum(file => file.Length);
// If Subdirectories are to be included
if (includeSubDir)
{
// Enumerate all sub-directories
totalSize += dInfo.EnumerateDirectories()
.Sum(dir => DirectorySize(dir, true));
}
return totalSize;
}