In the C/S architecture, asynchronous file operations may occur in both the traditional winform and wpf. If the file is small, write the operation code directly.
For large files, asynchronous operations are often performed. A progress bar or something is displayed on the interface. A backgroundworker is used in the background. Here we will tell you that. NET Framework4.5 supports asynchronous IO operations. This greatly simplifies the previous Asynchronous Method Code.
Use the backgroundworker code
Copy codeThe Code is as follows:
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 ");
}
The above should be the most basic operation. Is there a lot of code? Let's see how to write. NET Framework 4.5.
Copy codeThe Code is as follows:
Private async void Button_Click_2 (object sender, RoutedEventArgs 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 ('\\'))))
{
Await SourceStream. CopyToAsync (DestinationStream );
}
}
}
MessageBox. Show ("OK ");
}
Hope to help some people.