我写了一个应用程序,它接受一个主文件夹并复制主文件夹的所有子文件夹中的所有文件。它可以工作,但是当我复制很多文件时,表单将“暂时没有响应”直到它完成。
以下是我正在使用的代码。
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!");
}
答案 0 :(得分:1)
您需要查看Threading
。 http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx
答案 1 :(得分: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
}
}