A little more about File.Writeallbytes

Asked

Viewed 641 times

2

How to display progress by synchronizing the following function:

File.WriteAllBytes(string path, byte[] content);

This method should be called according to a System.Threading.Thread

Ex:

Thread wnd;
string wnd_file;
byte[] wnd_bytes;

void Install(string path, byte[] content){
   wnd_file=path; wnd_bytes=content;
   wnd = new Thread(new ThreadStart(BackgroundProgressTASK));
   wnd.Start();
}

void BackgroundProgressTASK(){
  File.WriteAllBytes(wnd_file, wnd_bytes);
}

So the application does not suffer any crashes during the time it writes the file!

1 answer

5


It does not. This method is even blocking. It must run completely without external interference. You can create thread (and this is not even the most recommended way of doing it) that will not solve. The only way is to create a method that will slowly write where you have control.

The question is a little confusing. To make the progress indicator it is not necessary to have a thread or other similar mechanism. If you want the entire application to remain free to perform the best way is to use an asynchronicity technique in the whole method that does what you want. Take an example in that reply.

Note that trying to run GUI with threads different you can’t run GUI in more than one thread. At least not under normal conditions. What you can do is use a BackgroudWorker (has an example of progress indicator). Simplifying would be something like this (I have not tested):

var backgroundWorker = new BackgroundWorker(); //estará fora do método de escrita

using (var stream = new FileStream(wnd_file, FileMode.OpenOrCreate)) {
    using (var writer = new BinaryWriter(stream)) {
        var remain = wnd_bytes.Length;
        var written = 0;
        while (remain > 0) {
            var size = Math.Min(4096, remain);
            writer.Write(wnd_bytes, written, size);
            written += size;
            remain -= size;
            backgroundWorker.ReportProgress(written * 100 / wnd_bytes.Length);
        }
    }
}

I put in the Github for future reference.

In the documentation there is an example of how to write a asynchronous writing method. But if I understand what you described, you don’t need this.

  • so your code helps me a lot but what I want is to simply create a program that would install another program without importing files of the type. zip or other!

  • 1

    Okay, if you still have any other questions, just ask around.

  • Another thing is I try to apply a thread to Webbrowser.Navigate("http://google.com") Thread starts but has no action in this function!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.