Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to learn WriteAllBytes progress

Tags:

c#

progress

Can I use a progress bar to show the progress of

File.WriteAllBytes(file, array)

in C#?

like image 562
Bora Avatar asked Mar 17 '13 22:03

Bora


1 Answers

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.

like image 135
siride Avatar answered Sep 28 '22 06:09

siride