Progress bar and file download

I have a large text file containing many lines of data. In my application, I open this file, read each line, matching the regular expression and displaying it in the Datagridview. The total number of generated lines is about 2000 (sometimes even more, so quite a lot).

Thus, all these operations require a rather large amount of time. Therefore, I moved this code to another thread using a background worker, and everything is fine, except that I want to show the download status in the execution line, where I fail.

I used the FileInfo class to get the length of the file, and then gave this value to Progressbar.Maximum . This does not seem to be the case, because the test file containing the lines "3" returns the length of the file "305". I do not understand how many time intervals I have to perform this way.

Code example:

 FileInfo ff = new FileInfo(openFileDialog1.FileName); int fsize= Convert.ToInt32(ff.Length); int val=1; pgbar_load.Invoke(new MethodInvoker(delegate { pgbar_load.Maximum = fsize; })); 

and in the loop:

 ++val; wk.ReportProgress(val); 

and then:

 private void bgwrkr_load_ProgressChanged(object sender, ProgressChangedEventArgs e) { pgbar_load.Value = e.ProgressPercentage; } 

So the two things I'm looking for:

  • Sets the maximum value for the progress bar.
  • Correctly set the step index.

Please suggest me a way to move forward.

+6
source share
1 answer

Save Progressbar.Maximum to 100. Then track your read data in int variable. Run a loop in the user interface thread (you can use a timer for this), which sets the percentage of completion by checking your read bytes. For instance. suppose you store your read bytes in int totalRead; , and int totalFileSize contains the size of your file.

 myProgressBar.Value = Convert.ToInt32(Math.Ceil(100d * totalRead/totalFileSize)); 

You can put this in a timer event handler. This will cause the progress bar to gradually increase to 100%. When the file reading is completed, turn off the timer.

+6
source

Source: https://habr.com/ru/post/925504/


All Articles