File.AppendText()慢

时间:2016-12-16 19:14:04

标签: c# streamwriter

我有一个大文件,其结构如下:

 Report 1  section 1
 Report 2  section 1
 Report 1  section 2
 Report 3  section 1
 Report 2  section 2
 and so on....

我必须将所有1组合在一起,将所有2组合在一起等,放入报告1,报告2,报告3.我别无选择,只能逐行进行。问题是它很慢。这是我用来编写文件的代码:

        using (StreamWriter sw = File.AppendText(newFileName))
                    { sw.WriteLine(line); }

我认为问题在于File.AppendText()正在减慢这个过程。我想知道是否有人对如何加快这一点有任何想法。

2 个答案:

答案 0 :(得分:4)

您似乎在为每次迭代打开该文件。试试这个:

using (StreamWriter sw = File.AppendText(path))
{
    while (condition)
    {
        sw.WriteLine("write your line here");
    }
}

正如Chris Berger评论的那样,你可以像这样嵌套使用

using (StreamWriter sw1 = File.AppendText(path1))
{
    using (StreamWriter sw2 = File.AppendText(path2))
    {
        while (condition)
        {
            if(writeInFile1)
                sw1.WriteLine("write your line here");
            else
                sw2.WriteLine("write your line here");
        }
    }
}

答案 1 :(得分:1)

正如您在Facundo's answer

中提到的那样
  

这是一个很好的解决方案但是我将有一个来自一个文件的五个或六个报告文件...

您可以使用多个using语句一次打开所有6个文件。

using (StreamReader sr = File.OpenText(source)
using (StreamWriter sw1 = File.AppendText(path1))
using (StreamWriter sw2 = File.AppendText(path2))
using (StreamWriter sw3 = File.AppendText(path3))
using (StreamWriter sw4 = File.AppendText(path4))
using (StreamWriter sw5 = File.AppendText(path5))
using (StreamWriter sw6 = File.AppendText(path6))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        if(line.StartsWith("Report 1")
        {
            sw1.WriteLine(line);
        }
        else if(line.StartsWith("Report 2")
        {
            sw2.WriteLine(line);
        }
        else if(line.StartsWith("Report 3")
        {
            sw3.WriteLine(line);
        }
        else if(line.StartsWith("Report 4")
        {
            sw4.WriteLine(line);
        }
        else if(line.StartsWith("Report 5")
        {
            sw5.WriteLine(line);
        }
        else if(line.StartsWith("Report 6")
        {
            sw6.WriteLine(line);
        }
        else
        {
            throw new InvalidDataException($"Line does not start with a report number: \n{line}");
        }
    }
}