我正在使用 xcopy 编写一个备份程序,因为有很多大文件需要一段时间,所以我想展示一下进度。当我尝试使用 StreamReader 获取标准输出时,它在调试时出现此错误消息。“不能在流程流上混合同步和异步操作。”
public void backup_worker_DoWork(object sender, DoWorkEventArgs e)
{
int loop = 1;
backup_worker.WorkerReportsProgress = true;
Process xcopy = new Process();
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.CreateNoWindow = true;
startinfo.UseShellExecute = false;
startinfo.RedirectStandardError = true;
startinfo.RedirectStandardOutput = true;
startinfo.FileName = Environment.CurrentDirectory + "\\xcopy.exe";
startinfo.Arguments = '"' + source + '"' + " " + '"' + target + '"' + " " + "/s /e /y";
xcopy.StartInfo.RedirectStandardOutput = true;
xcopy.StartInfo = startinfo;
xcopy.Start();
xcopy.BeginErrorReadLine();
xcopy.BeginOutputReadLine();
StreamReader sr = xcopy.StandardOutput;
while (loop > 0)
{
progress = sr.ReadLine();
output_list.Items.Add(progress);
}
xcopy.OutputDataReceived += new DataReceivedEventHandler(backup_worker_OutputDataRecieved);
xcopy.ErrorDataReceived += new DataReceivedEventHandler(backup_worker_ErrorDataReceived);
xcopy.WaitForExit();
backup_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backup_worker_RunWorkerCompleted);
}
void backup_worker_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
}
void backup_worker_OutputDataRecieved(object sender, DataReceivedEventArgs e)
{
}
void backup_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Completed");
}
请帮忙。提前致谢