【发布时间】:2012-05-18 01:45:40
【问题描述】:
我正在寻找一种在将文件从一个位置复制到另一个位置时更新进度条的方法。
我正在BackgroundWorker 中进行复制,并且还在后台更新进度条。我尝试使用 file.length 来获取文件大小并使用它来计算百分比并以这种方式更新栏,但没有任何乐趣。
我附上代码,任何帮助将不胜感激,谢谢。
namespace Copier
{ 公共部分类Form1:表格 { 公共表格1() { 初始化组件(); }
// Declare for use in all methods
public string copyFrom;
public string copyTo;
private void btnCopyFrom_Click(object sender, EventArgs e)
{
// uses a openFileDialog, openFD, to chose the file to copy
copyFrom = "";
openFD.InitialDirectory = @"C:\Documents and Settings\user\My Documents";
openFD.FileName = "";
//openFD.ShowDialog();
if (openFD.ShowDialog() == DialogResult.Cancel)
{
MessageBox.Show("cancel button clicked");
}
else
{
// sets copyFrom = to the file chosen from the openFD
copyFrom = openFD.FileName;
// shows it in a textbox
txtCopyFrom.Text = copyFrom;
}
}
private void btnCopyTo_Click(object sender, EventArgs e)
{
//uses folderBrowserDialog, folderBD, to chose the folder to copy to
copyTo = "";
this.folderBD.RootFolder = System.Environment.SpecialFolder.MyComputer;
this.folderBD.ShowNewFolderButton = false;
//folderBD.ShowDialog();
//DialogResult result = this.folderBD.ShowDialog();
if (folderBD.ShowDialog() == DialogResult.Cancel)
{
MessageBox.Show("cancel button clicked");
}
else
{
// sets copyTo = to the folder chosen from folderBD
copyTo = this.folderBD.SelectedPath;
//shows it in a textbox.
txtCopyTo.Text = copyTo;
}
}
private void btnCopy_Click(object sender, EventArgs e)
{
copyBGW.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
//=================================================================
// BackGroundWorkers
//=================================================================
private void copyBGW_DoWork(object sender, DoWorkEventArgs e)
{
try
{
// copies file
string destinatationPath = Path.Combine(copyTo, Path.GetFileName(copyFrom));
File.Copy(copyFrom, destinatationPath);
MessageBox.Show("File Copied");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
或者有人可以告诉我一种方法,让进度条自己走,这样它就表明表单没有冻结?
已清理代码
感谢您到目前为止的意见
【问题讨论】:
标签: c# .net visual-studio-2010