Can I use a progress bar to show the progress of
File.WriteAllBytes(file, array)
in C#?
No.
You'll need to write the bytes in chunks using a loop. Something like the following should get you started. Note that this needs to be running in a background thread. I you are using WinForms, you can use a BackgroundWorker
.
using(var stream = new FileStream(...))
using(var writer = new BinaryWriter(stream)) {
var bytesLeft = array.Length; // assuming array is an array of bytes
var bytesWritten = 0;
while(bytesLeft > 0) {
var chunkSize = Math.Min(64, bytesLeft);
writer.WriteBytes(array, bytesWritten, chunkSize);
bytesWritten += chunkSize;
bytesLeft -= chunkSize;
// notify progressbar (assuming you're using a background worker)
backgroundWorker.ReportProgress(bytesWritten * 100 / array.Length);
}
}
EDIT: as Patashu pointed out below, you can also you tasks and await. I think my method is fairly straightforward and doesn't require any additional thread stuff (besides the one background thread you need to do the operation). It's the traditional way and works well enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With