The first thing to do is figure out how long the file has been using FileInfo,
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx
FileInfo fileInfo = new FileInfo(file); long length = fileInfo.Length;
I suggest you do it this way
private long currentPosition = 0; private void UpdateProgressBar(int lineLength) { currentPosition += line.Count; // or plus 2 if you need to take into account carriage return progressBar.Value = (int)(((decimal)currentPosition / (decimal)length) * (decimal)100); } private void CopyFile() { progressBar.Minimum = 0; progressBar.Maximum = 100; currentPosition = 0; using (StreamReader sr = new StreamReader(file,System.Text.Encoding.ASCII)) { while (sr.EndOfStream == false) { line = sr.ReadLine(); UpdateProgressBar(line.Length); if (line.IndexOf(start) != -1) { using (StreamWriter sw = new StreamWriter(DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + "cut")) { sw.WriteLine(line); while (sr.EndOfStream == false && line.IndexOf(end) == -1) { line = sr.ReadLine(); UpdateProgressBar(line.Length); sw.WriteLine(line); } } richTextBox1.Text += "done ..." + "\n"; break; } } } }
which calculates the percentage of a read file and sets a progress bar for this value. Then you need not worry about whether the length is long, and the progress bar uses int.
If you donβt want to truncate the value, then do it (casting to int above will always truncate decimal numbers and thus round off)
progressBar.Value = (int)Math.Round(((decimal)currentPosition / (decimal)length) * (decimal)100), 0);
Is it on the background thread? Don't forget that you will need to call this.Invoke to update the progress bar, otherwise you will get a cross-thread exception.
source share