[英]Copying With Progress Bar not working
我有點小問題。 我正在嘗試使用狀態欄將表單的內容從A點復制到B的表單。 現在復制可以正常工作,但是狀態欄什么也沒做。任何人都有線索嗎?
public partial class Form4A : Form
{
public Form4A()
{
InitializeComponent();
OtherSettings();
BackgroundWorker.RunWorkerAsync(); // Starts wow copying
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string SourcePath = RegistryRead.ReadOriginalPath();
string DestinationPath = RegistryRead.ReadNewPath();
if (!Directory.Exists(SourcePath))
{
for (int i = 1; i <= 100; i++)
{
//Now 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));
BackgroundWorker.ReportProgress(i);
}
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}
您說: if (!Directory.Exists(DestinationPath))
。 這意味着,如果存在目標路徑,則將永遠不會執行循環。 在測試代碼之前,請確保刪除DestinationPath!
編輯:
if (Directory.Exists(SourcePath)) {
//Now Create all of the directories
string[] allDirectories = Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories);
string[] allFiles = Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories);
int numberOfItems = allDirectories.Length + allFiles.Length;
int progress = 0;
foreach (string dirPath in allDirectories) {
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
progress++;
BackgroundWorker.ReportProgress(100 * progress / numberOfItems);
}
//Copy all the files
foreach (string newPath in allFiles) {
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));
progress++;
BackgroundWorker.ReportProgress(100 * progress / numberOfItems);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.