How to learn WriteAllBytes progress

南楼画角 提交于 2019-12-19 19:31:31

问题


Can I use a progress bar to show the progress of

File.WriteAllBytes(file, array)

in C#?


回答1:


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.




回答2:


Since WriteAllBytes is a synchronous method, you can do nothing and know nothing about the operation until it finishes.

What you need to do is have a method like WriteAllBytes, but written to be asynchronous, such as in http://msdn.microsoft.com/en-AU/library/jj155757.aspx . You can have your asynchronous method every so often stop and report its progress to the GUI, as it runs separately.



来源:https://stackoverflow.com/questions/15467135/how-to-learn-writeallbytes-progress

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!