0

我编写了一个应用程序,它采用一个主文件夹并复制主文件夹的所有子文件夹中的所有文件。它可以工作,但是当我复制大量文件时,表单将在一段时间内“无响应”,直到完成。

这是我正在使用的代码。

    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!");
        }
4

2 回答 2

1

你需要调查一下Threadinghttp://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

于 2012-09-13T18:31:40.720 回答
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
        }
    }
于 2012-09-13T18:33:40.517 回答