Read / write text file in C #

I have a function that reads a large text file, splits the part (from a specific start and end) and saves the divided data into another text file. Since the file is too large, I need to add a progress bar when reading a stream and another when writing split text to another .Ps.start and end file are given datetime !!

using (StreamReader sr = new StreamReader(file,System.Text.Encoding.ASCII)) { while (sr.EndOfStream == false) { line = sr.ReadLine(); 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(); sw.WriteLine(line); } } richTextBox1.Text += "done ..." + "\n"; break; } } } 
+4
source share
1 answer

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.

+10
source

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


All Articles