C# 线程复制文件!使用进度条同时显示单个文件的复制进度,和总体进度。复制多文件(文件数量大约1000以上)时候程序假死,求高手优化
本来我是没使用线程的,后来会假死,就是突然卡住,进度条都不动了,然后突然一会就显示备份成功,用了线程之后虽然不一定会假死,但是复制时间却是原来的两倍,所以,求高手优化,目前之是单线程,本人菜鸟,还不会用多线程!
//线程开始启动调用,主方法Copy
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Copy(@txtSource.Text.Trim(), @txtDest.Text.Trim());
if (progressBar1.Value == progressBar1.Maximum)
{
DateTime Edt = DateTime.Now;
TimeSpan ts = Edt - Sdt;
MessageBox.Show("备份成功,共用时(" + ts.Seconds + "秒)");
count = 0;
leng = 0;
}
}
public void Copy(String source, String destination)
{
DirectoryInfo info = new DirectoryInfo(source);
foreach (FileSystemInfo fsi in info.GetFileSystemInfos())
{
//目标路径destName = 目标文件夹路径 + 原文件夹下的子文件(或文件夹)名字
//Path.Combine(string a ,string b) 为合并两个字符串
String destName = Path.Combine(destination, fsi.Name);
//如果是文件类,就复制文件
if (fsi is FileInfo)
{
lblMessge.Refresh();
lblParent.Refresh();
lblMessge.Text ="正在复制:"+ fsi.Name;
Getlength(fsi.FullName, destName);
// File.Copy(fsi.FullName, destName, true);
leng += count;
progressBar1.Value = leng;
lblParent.Text = (progressBar1.Value * 100) / progressBar1.Maximum + "%";
}
//如果不是 则为文件夹,继续调用文件夹复制函数,递归
else
{
Directory.CreateDirectory(destName);
Copy(fsi.FullName, destName);
}
}
}
private void Getlength(string sources, string destname)
{
FileStream ofile = new FileStream(sources, FileMode.Open, FileAccess.Read);
FileStream nfile = new FileStream(destname, FileMode.Create, FileAccess.Write);
progressBar2.Maximum=Convert.ToInt32(ofile.Length);
byte[] buffer = new byte[1024];
int plength = 0;
do
{
plength += ofile.Read(buffer, 0, 1024);
progressBar2.Value = plength;
nfile.Write(buffer, 0, 1024);
} while (plength < ofile.Length);
}
谁帮我看看怎么才能在复制多文件的时候不假死,如果用线程,是否能跟原来用的时间一样!