小编wil*_*ien的帖子

使用streamreader/streamwriter在C#中逐行编写文件非常慢

我编写了一个Winform应用程序,它读取文本文件的每一行,使用行上的RegEx进行搜索和替换,然后将其写回新文件.我选择了"逐行"方法,因为有些文件太大而无法加载到内存中.

我正在使用BackgroundWorker对象,因此可以使用作业的进度更新UI.下面是代码(为简洁起见省略了部分),它处理读取然后输出文件中的行.

public void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Details of obtaining file paths omitted for brevity

    int totalLineCount = File.ReadLines(inputFilePath).Count();

    using (StreamReader sr = new StreamReader(inputFilePath))
    {
      int currentLine = 0;
      String line;
      while ((line = sr.ReadLine()) != null)
      {
        currentLine++;

        // Match and replace contents of the line
        // omitted for brevity

        if (currentLine % 100 == 0)
        {
          int percentComplete = (currentLine * 100 / totalLineCount);
          bgWorker.ReportProgress(percentComplete);
        }

        using (FileStream fs = new FileStream(outputFilePath, FileMode.Append, FileAccess.Write)) …
Run Code Online (Sandbox Code Playgroud)

c# streamwriter streamreader

2
推荐指数
1
解决办法
2825
查看次数

标签 统计

c# ×1

streamreader ×1

streamwriter ×1