I am trying to read a file and show updates using a progress bar. I keep getting this error reading last part of the file:
System.ArgumentOutOfRangeException: 'Value of '7340032' is not valid for 'Value'. 'Value' should be between 'minimum' and 'maximum'. Parameter name: Value'
at this location
progressBar.Value = position;
this is my whole code
private async void readFileWithProgressBar(
string fileToRead, ProgressBar progressBar)
{
var fileSize = (int)(new FileInfo(fileToRead).Length);
// Set the maximum value of the progress bar to the file size
progressBar.Maximum = fileSize;
// Now read the file with FileStream functions
int position = 0;
int blockSize = 1024 * 1024; // Read 1 megabyte at a time
byte[] allData = new byte[fileSize];
using (var fs = new FileStream(fileToRead, FileMode.Open))
{
var bytesLeft = fileSize;
while (bytesLeft > 0)
{
await fs.ReadAsync(
allData, position, Math.Min((int)bytesLeft, blockSize));
// Advance the read position
position += blockSize;
// Update the progress bar
progressBar.Value = position; //ERROR IS HERE
bytesLeft -= blockSize;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
readFileWithProgressBar(@"<path>\test.txt",progressBar1);
}
My code executes almost to the end but then all of a sudden it stops and gives that error above.