C# - 在特定行之后将一行写入文本文件

时间:2015-02-20 07:54:15

标签: c#

我在下面有以下代码,我正在努力确保

line(sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype)) ;

line(sw.WriteLine(errLine));之后写入文本文件。

在创建文件时,行没有以正确的顺序写入文件,即 sw.WriteLine("测试ID:" + testid +"" +"事件失败:" + testtype) - 此行首先出现 sw.WriteLine(errLine) - 出现在第二位。

只是想知道你能帮忙吗。

using (StreamWriter sw = File.AppendText(@"D:\Temp\Final.txt"))

try
{                                   
   string evnt = Convert.ToString(eventid);
   string test = Convert.ToString(testid);
   Queue<string> lines = new Queue<string>();
   using (var filereader = new StreamReader(@"D:\Temp\Outlook.txt"))
   {
       string line;
       while ((line = filereader.ReadLine()) != null)
       {
           if (line.Contains(evnt) && line.Contains(test) &&  evnt != oldevent)                                             
           {
               sw.WriteLine("----- ERROR -----");
               foreach (var errLine in lines)
                   sw.WriteLine(errLine);
                   oldevent = evnt;
                   sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype);                                                    
               sw.WriteLine(line);
               sw.WriteLine("-----------------");
           }
           lines.Enqueue(line);

           while (lines.Count > 10)
               lines.Dequeue();
       }
   }
}

3 个答案:

答案 0 :(得分:0)

可能 Linq 是一个解决方案吗?这样的事情:

  var source = File
    .ReadLines(@"D:\Temp\Outlook.txt")
    .Select(line => {
       //TODO: put actual code here 
       if (line.Contains("Something to find"))
         return new String[] {"Some caption", line, "More text"};
       else
         return new String[] {line}; 
    })
    .SelectMany(line => line);

  File.WriteAllLines(@"D:\Temp\Final.txt", source);

答案 1 :(得分:0)

文件正在从上到下书写。试试这条线 在行之前的{for循环中} sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype); foreach (var errLine in lines)

答案 2 :(得分:0)

如上所述,你可以在下面做:

File.WriteAllLines(@"D:\Temp\Final.txt", File.ReadLines(@"D:\Temp\Outlook.txt")
            .Select(line => line.Contains("Something to find")
                    ? new String[] {"Some caption", line, "More text"}
                    : new String[] {line};
            )
            .SelectMany(line => line));