问题描述
publicpartialclassForm3:Form{publicintTotalBytes=0;publicintCurrentBytes=0;BackgroundWorkerBgw=null;publicForm3(){InitializeComponent();Bgw=newBackgroundWorker();Bgw.WorkerSupportsCancellation=true;Bgw.WorkerReportsProgress=true;Bgw.DoWork+=newDoWorkEventHandler(Bgw_DoWork);Bgw.RunWorkerCompleted+=newRunWorkerCompletedEventHandler(Bgw_RunWorkerCompleted);Bgw.ProgressChanged+=newProgressChangedEventHandler(Bgw_ProgressChanged);Bgw.RunWorkerAsync();}voidBgw_ProgressChanged(objectsender,ProgressChangedEventArgse){this.progressBar1.Maximum=Convert.ToInt32(TotalBytes);this.progressBar1.Value=e.ProgressPercentage;}voidBgw_RunWorkerCompleted(objectsender,RunWorkerCompletedEventArgse){MessageBox.Show("下载完成!");//this.Close();}voidBgw_DoWork(objectsender,DoWorkEventArgse){FileStreamsouce=null;FileStreamdest=null;try{souce=newFileStream("E:\办公软件\ue_chinese19.10.exe",FileMode.Open);dest=newFileStream("D:\ue_chinese19.10.exe",FileMode.Create);TotalBytes=Convert.ToInt32(souce.Length);byte[]by=newbyte[1024];intosize=souce.Read(by,0,(int)by.Length);while(osize>0){CurrentBytes+=1024;dest.Write(by,0,osize);(senderasBackgroundWorker).ReportProgress(CurrentBytes);osize=souce.Read(by,0,(int)by.Length);Thread.Sleep(1);}souce.Flush();souce.Close();dest.Flush();dest.Close();}catch(Exceptionex){souce.Flush();souce.Close();//throwex;}}privatevoidbutton1_Click(objectsender,EventArgse){Bgw.RunWorkerAsync();}//拔出的时候等20秒左右编译器报错程序退出
解决方案
解决方案二:
大致看了下,你这是从E盘拷贝文件到D盘拔掉设备(应该是D或E),而此时复制没有完成,线程还在后台执行,找不到文件源,或复制过来的文件没地方放,就会出问题了
解决方案三:
HResult=-2147023890Message=文件所在的卷已被外部更改,因此打开的文件不再有效。Source=mscorlibStackTrace:在System.IO.__Error.WinIOError(Int32errorCode,StringmaybeFullPath)在System.IO.FileStream.WriteCore(Byte[]buffer,Int32offset,Int32count)在System.IO.FileStream.FlushWrite(BooleancalledFromFinalizer)在System.IO.FileStream.Dispose(Booleandisposing)在System.IO.FileStream.Finalize()这里明显是某个地方调用了Stream的Dispose方法,目测应该是垃圾回收机制起作用了!只是释放资源的时候报错了
解决方案四:
这哪里诡异了?