It is necessary to show the progress of the implementation of this line of code through the progressBar1 component

listBox1.Items.AddRange(File.ReadAllLines(name, Encoding.Default)); 
  • one
    ReadAllLines does not inform about progress, and it should work quickly if you do not load a file of very large size. - Monk
  • So the fact is that this is a very large text file. Then please tell me which procedure or function to use so that it notifies of progress? - Tim

2 answers 2

To begin with, if the file is really very large, I would not advise shipping it to the ListBox . In addition, reading the entire file occurs entirely, and does not give you asynchrony, so you need to divide the reading into pieces.

You will have to make your procedure asynchronous, so that the window does not hang:

 var batchSize = 100; // найдите хорошее значение экспериментально using (var r = File.OpenText(path)) { while (true) { var batch = await GetBatch(r, batchSize); if (batch == null) break; listBox1.Items.AddRange(batch); // тут обновите прогресс await Task.Yield(); } } 

Auxiliary function:

 async Task<string[]> GetBatch(StreamReader r, int batchSize) { var batch = new List<string>(); for (int i = 0; i < batchSize; i++) { var line = await r.ReadLineAsync(); if (line == null) break; batch.Add(line); } if (batch.Count == 0) return null; return batch.ToArray(); } 

    You can load the file line by line. Then you will see some progress, but to know how much is left, you need to know the total number of lines.

    To get the number of lines, you can use this: https://stackoverflow.com/questions/119559/determine-the-number-of-lines-within-a-text-file

    I think this should work quickly even on a large file.

    If all the same, reading the number of lines is a long process, then you can start reading the lines in one stream without first knowing the number of lines in the file (Write 1 line of N in the progress bar), and start counting in another thread -v lines. When you recognize the number of lines, update the progress bar (Add the total number of lines, for example, 1 line out of 10,000 is read).