[英]C# - writing a line to text file after a specific line
我在下面有以下代碼,我正在努力確保
line(sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype)) ;
line(sw.WriteLine(errLine));
之后寫出文本文件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();
}
}
}
可能是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);
文件是從上到下編寫的。 嘗試使用此行sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype);
在for循環之前,在行之前: foreach (var errLine in lines)
如上所述,您可以在下面執行:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.