简体   繁体   中英

C# - writing a line to text file after a specific line

I have the following code below and I am trying to ensure that the

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

is written out to the text file after the line(sw.WriteLine(errLine)); .

At the moment when the file is created the lines are not being written to the file in the right order ie sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype) - this line appears first sw.WriteLine(errLine) - appears second.

Just wondering could you help.

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();
       }
   }
}

May be Linq is a solution? Something like that:

  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);

File is being written from up to bottom. Try taking this line sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype); out of the for loop, before line: foreach (var errLine in lines)

As above you can do below:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM