StreamReader对于大文件来说非常慢

jLy*_*ynx 1 c# streamreader

我想读一个文件,在这种情况下是3mb,这需要大约50-60秒,这似乎非常慢.有谁知道如何让这更快?

string text = null;
using (StreamReader sr = new StreamReader(file, Encoding.Default))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        text += (line);
        backgroundWorker1.ReportProgress(text.Length);
    }
}
Run Code Online (Sandbox Code Playgroud)

我还需要使用后台工作程序,以便我可以报告已加载的百分比(对于大约500mb到1gb的文件)

RB.*_*RB. 5

使用StringBuilder创建你的行 - 它比字符串连接更高效.

using System.Text;

//...

StringBuilder text = new StringBuilder();
using (StreamReader sr = new StreamReader(file, Encoding.Default))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        text.Append(line);
        backgroundWorker1.ReportProgress(text.Length);
    }
}

// ...
// Do something with the file you have read in.
Console.WriteLine(text.ToString());
Run Code Online (Sandbox Code Playgroud)