Do the copy in a BackgroundWorker class (RunWorkerAsync) and use the ReportProgess event to notify your UI's Progress bar of the percentage complete....
Drag a BackgroundWorker control onto your form, you will see how it works...
Rob
-
Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......
My HARD DRIVE has a built-in 32MB BUFFER built-in. I can write a file in a few seconds, then shut down the machine. The drive doesn't stop until the buffer is empty.
Hint: Read BLOCKS of data. Set up a BLKSIZE, and keep track of it's location.
Uh, well you are setting the maximum value of the progress bar to the size of the file in bytes and the value of the bar to the number of bytes written.
I guess that's one way to do it.
Why don't you instead simply have the bars values go from 0 to 100 as in 0-100% which makes more sense.
Bytes Written / Total File Size * 100 = The completion percentage
and it doesn't matter how many bytes you transfer per go obviously.
There are many options, but I think BackgroundWorker is the one for you. However, you should copy the whole file at once, not a byte at a time. Use ReportProgress if you are copying say 10 files. Assuming equal size, increment the progress bar by 10% each time one completes.
You say this should be a simple task... But if you look closely, even Microsoft and Apple can't get it right... How many times have you sat stairing at a ProgressBar for over a minute, waiting for the ONE second remaining to complete? It's not easy at all.
Rob
-
Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......
@OP: Yes, please don't slow down the process of copying a file just to show a progress bar. You will not create the most accurate progress bar ever made, and that's ok. Really, it's ok, move on with your project and your life
Copy the file in chunks on one thread and use callbacks to set the progress bar value.
On my own laptop through trial and error I found that the lowest amount I could read but still be io efficient was about half a meg.
Code:
//Code was not complied\checked, more of guide, notice I havnt even closed the streams
void Copy()
{
int halfAMeg = (int)(1024 * 1024 * 0.5);
FileStream strIn = new FileStream("filePathIn", FileMode.Open);
FileStream strOut = new FileStream("filePathOut", FileMode.Create);
byte[] buf = new byte[halfAMeg];
while (strIn.Position < strIn.Length)
{
int len = strIn.Read(buf, 0, buf.Length);
strOut.Write(buf, 0, len);
SetProBar(strIn.Position, strIn.Length);
}
}
private delegate void SetProBar_CallBack(long val,long max);
private void SetProBar(long val, long max)
{
if (progressBar.InvokeRequired)
{
SetProBar_CallBack callBack = new SetProBar_CallBack(SetProBar);
this.Invoke(callBack, new object[] { val, max });
}
else
{
progressBar.Maximum = Int32.MaxValue;
progressBar.Value = (int)(Int32.MaxValue / (max / val));
}
}
Bookmarks