在C/S架構(gòu)中,不管是傳統(tǒng)的winform還是wpf都可能會(huì)遇到進(jìn)行異步操作文件的時(shí)候。文件小還好說(shuō),直接寫操作代碼。
如果是大文件很多時(shí)候做成異步的操作。在界面上顯示一個(gè)進(jìn)度條什么的,后臺(tái)使用一個(gè)backgroundworker來(lái)做。在這里告訴大家在.NET Framework4.5中支持異步IO的操作。大大簡(jiǎn)化之前些的異步方法代碼。
View Code
private void Button_Click_3(object sender, RoutedEventArgs e)
{
System.ComponentModel.BackgroundWorker bak = new System.ComponentModel.BackgroundWorker();
bak.DoWork += bak_DoWork;
bak.RunWorkerCompleted += bak_RunWorkerCompleted;
bak.RunWorkerAsync();
}
void bak_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
string sourceDir = @"E:\";
string endDir = @"F:\";
foreach (string filename in Directory.EnumerateFiles(sourceDir))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(endDir + filename.Substring(filename.LastIndexOf('\\'))))
{
SourceStream.CopyTo(DestinationStream);
}
}
}
}
void bak_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
MessageBox.Show("ok");
}