yosafat yosafat - 2 months ago 8
C# Question

C# How to append only the end of text file and in specific position?

i want to change status from OK to NG,

IPen ID Datetime Status
50 Wednesday, September 21, 2016 08:56:45 OK
IPen ID Datetime Status
50 Wednesday, September 21, 2016 08:56:51 OK


this is file on my report.txt. my expectation is how we delete this last line with c# ?

IPen ID Datetime Status
50 Wednesday, September 21, 2016 08:56:51 OK


and how to append OK status change into NG status? the result i hope is like this :

IPen ID Datetime Status
50 Wednesday, September 21, 2016 08:56:45 NG


this is my code :

var lines = File.ReadAllLines(Fullpath);
File.WriteAllLines(Fullpath, lines.Take(lines.Length - 1).ToArray());
DisplayData(MessageType.Incoming, lines[lines.Length - 1]);

var text = new StringBuilder();

foreach (string s in File.ReadAllLines(Fullpath))
{
text.AppendLine(s.Replace("OK", "NG"));
}

using (var file = new StreamWriter(File.Create(Fullpath)))
{
file.Write(text.ToString());
}


this code will append all of "OK" change into "NG". not like that i want, but i want to delete the last result and change only two last result from "OK" to "NG" not all OK change to NG. any suggestion or solution for me? thanks for attention and help.

Answer

Since you're already reading the entire file into memory, you could convert it to a list, remove from the end, and iterate in reverse to update the last two entries:

var lines = File.ReadAllLines(Fullpath).ToList();

// Remove as many lines as you'd like from the end
if (lines.Count > 2)
{
    lines.RemoveRange(lines.Count - 2, 2);
}

// Iterate backwards through the list until we've updated 2 (or more or less) lines
var linesUpdated = 0;

for (var i = lines.Count - 1; i >= 0 && linesUpdated < 2; i--)
{
    if (lines[i].Contains("OK"))
    {
        lines[i] = lines[i].Replace("OK", "NG");
        linesUpdated++;
    }
}

File.WriteAllLines(Fullpath, lines.ToArray());