I'm looking for a way to update my progress bar while copying a file from one location to another.
I'm doing the copy in a BackgroundWorker
and have the progress bar updating in the background as well. I've tried using the file.length to get the file size and use that to work the percentage and update the bar that way but to no joy.
I'm attaching the code and any help would be greatly appreciated, Thank you.
namespace Copier
{ public partial class Form1 : Form { public Form1() { InitializeComponent(); }
// 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);
}
}
}
Or could someone show me a way to just make the progress bar go by its self so it shows that the form hasn't frozen?
Have cleaned up the code
Thanks for the input so far