2012-09-13 95 views
0

我編寫了一個應用程序,它接收主文件夾並複製主文件夾所有子文件夾中的所有文件。它的作品,但當我複製了很多文件的形式將是「沒有響應」一段時間,直到它完成。確保Windows窗體響應

這是我正在使用的代碼。

private void buttonCopy_Click(object sender, RoutedEventArgs e) 
    { 
     try 
     { 
      ArrayList existingFiles = new ArrayList(); 
      string existingFileName = ""; 
      string thePath = folderSelect.Text; 
      DirectoryInfo di = new DirectoryInfo(thePath); 
      FileInfo[] allFiles = di.GetFiles("*.*", System.IO.SearchOption.AllDirectories); 

      foreach (FileInfo file in allFiles) 
      { 
       string fullName = file.FullName; 
       string fileName = System.IO.Path.GetFileName(fullName); 
       bool fileExists; 
       fileExists = File.Exists(folderSave.Text + System.IO.Path.DirectorySeparatorChar + fileName); 
       if (!fileExists) 
       { 
        file.CopyTo(folderSave.Text + System.IO.Path.DirectorySeparatorChar + fileName); 
       } 
       else 
       { 
        existingFileName += fileName + "\n"; 
        existingFiles.Add(existingFileName); 
       } 

      } 
      if (existingFiles.Count != 0) 
      { 
       System.Windows.MessageBox.Show(existingFiles.Count + " Files already exists!\n\n" + existingFileName); 
      } 
      System.Windows.MessageBox.Show("Files copied successfully!"); 
     } 

回答

1

您可以asynchnous治療嘗試

public class AsyncCopy 
    { 
     public delegate void CopyDelegate(string sourceFile, string destFile); 

     public static void AsynFileCopy(string sourceFile, string destFile) 
     { 
      CopyDelegate del = new CopyDelegate(FileCopy); 
      IAsyncResult result = del.BeginInvoke(sourceFile, destFile, CallBackAfterFileCopied, null); 
     } 

     public static void FileCopy(string sourceFile, string destFile) 
     { 
      // Add here your code for copy 
     } 

     public static void CallBackAfterFileCopied(IAsyncResult result) 
     { 
      // Add here your callback logic 
     } 
    }