C# 文件复制进度条未更新。文件拷贝工作正常
我正在写一份申请书来复制一个文件。我有文件复制没有任何问题,但由于某种原因,进度条没有更新。我正在使用后台工作程序。代码如下:C# 文件复制进度条未更新。文件拷贝工作正常,c#,windows,winforms,C#,Windows,Winforms,我正在写一份申请书来复制一个文件。我有文件复制没有任何问题,但由于某种原因,进度条没有更新。我正在使用后台工作程序。代码如下: private void bgWorker_DoWork(object sender, DoWorkEventArgs e) { // Gets the size of the file in bytes. Int64 iSize = strInputFile.Length; //
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Gets the size of the file in bytes.
Int64 iSize = strInputFile.Length;
// Keeps track of the total bytes downloaded so we can update the progress bar.
Int64 iRunningByteTotal = 0;
// Open the input file for reading.
using (FileStream InputFile = new FileStream(strInputFile, FileMode.Open, FileAccess.Read, FileShare.None))
{
// Using the FileStream object, we can write the output file.
using (FileStream OutputFile = new FileStream(strOutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
// Loop the stream and get the file into the byte buffer.
int iByteSize = 0;
byte[] byteBuffer = new byte[iSize];
while ((iByteSize = InputFile.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
// Write the bytes to the file system at the file path specified.
OutputFile.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;
// Calculate the progress out of a base "100."
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);
// Update the progress bar.
bgWorker.WorkerReportsProgress = true;
bgWorker.ReportProgress(iProgressPercentage);
}
// Close the output file.
OutputFile.Close();
}
// Close the input file.
InputFile.Close();
}
}
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// We will increase the progress bar when work progress is reported.
pbCopyProgress.Value = e.ProgressPercentage;
pbCopyProgress.Text = (e.ProgressPercentage.ToString() + " %");
}
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Disable the Copy button once the file has been copied.
MessageBox.Show("The file: "+strOutputFile+" has been copied");
btnCopy.Enabled = false;
}
我发现我需要初始化我的后台工作者事件处理程序,以修复我遇到的问题。我只需要在form load事件中添加以下三行:
bgWorker.DoWork += bgWorker_DoWork;
bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
bgWorker.ProgressChanged += bgWorker_ProgressChanged;
此行
bgWorker.WorkerReportsProgress=true
应该在bgWorker\u-DoWork
方法之外,可能在窗体的构造函数中(通常是以“可视化”方式而不是以编程方式执行此操作)。请尝试替换bgWorker.WorkerReportsProgress=true代码>在您的表单中,我们已经修复了bgWorker.WorkerReportsProgress=true;是否添加了bgWorker.RunWorkerAsync()代码>方法??如何从字符串文件名获取文件大小?(Int64 iSize=strInputFile.Length)作为将来的参考,您可以使用Visual Studio表单编辑器创建Backgroundworker对象并自动连接所有事件处理程序-Backgroundworker位于表单工具箱中,与任何其他表单控件(按钮、文本框等)一样工作,除了它在运行时在窗体上实际上不可见之外。