C#如何只追加文本文件的末尾和特定位置?

时间:2016-09-21 02:05:20

标签: c# visual-studio

我想将状态从OK更改为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

这是我的report.txt上的文件。我的期望是我们如何用c#删除最后一行?

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

以及如何将OK状态更改添加到NG状态?我希望的结果是这样的:

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

这是我的代码:

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

此代码会将所有“OK”更改为“NG”。不是我想要的,但我想删除最后的结果,只将最后两个结果从“OK”更改为“NG”并非所有OK都改为NG。对我有什么建议或解决方案吗?感谢关注和帮助。

4 个答案:

答案 0 :(得分:2)

由于您已经将整个文件读入内存,因此您可以将其转换为列表,从末尾删除,然后反向迭代以更新最后两个条目:

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

答案 1 :(得分:2)

不是更新所有行,而是确定最后一行然后更新。

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();
var data = File.ReadAllLines(Fullpath);
var lines = data.Take(data.Count() - 2);
var last = lines.Last();

foreach (string s in lines)
{
    if(s.Equals(last))
    {
        text.AppendLine(s.Replace("OK", "NG"));
    }
    else
    {
        text.AppendLine(s);
    }
}

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

enter image description here

答案 2 :(得分:1)

简单的方法: -

var lines = File.ReadAllLines(path);
if (lines.Length > 0)
{
  lines[lines.Length - 1] = lines[lines.Length - 1].Replace("OK", "NG");
}
File.WriteAllLines(path, lines);

删除最后两行

File.WriteAllLines(path, File.ReadAllLines(path).ToList().Take(lines.Count-2).ToArray())

但是你可能想要开始将行解析为对象,对对象进行任何更改,然后将它们序列化为文本行

答案 3 :(得分:1)

你不能“追加”某事。

您需要将整个文件读入一个字符串数组(每行一个),然后更改所需的行,然后在现有文件上重写整个内容。

// Read in whole contents of file.
var lines = File.ReadAllLines(Fullpath);

// Alter the lines you want to.
//Remove the last two rows (headers and data)
if (lines.Length > 2) lines = lines.ToList().Take(lines.Length - 2).ToArray();

// If lines contains 1 or more line in the file, replace any occurrence of OK, with NG.
if (lines.Length >= 1) lines[lines.Length - 1] = lines[lines.Length - 1].Replace("OK", "NG");

// Now write the contents of the file you have here in RAM back over the original file.
File.WriteAllLines(Fullpath, lines);

我建议使用更强大的方法来编辑这些日志。如果正在编写的记录稍后更改为包含两个写出OK值的列,则会出现问题。在这种情况下,你会改变它们。 替代方案是:

  • 正如@ keith-nicholas建议的那样,将您的数据系列化为对象并将其用于编辑。
  • 或者从您正在编辑的行上方的行中获取列起始位置。然后将其用作参考点。 对于Instance,要编辑最后一行:

    // This assumes those column headers are above each line
    if (lines.Length >= 2)
    {
        // Get the string starting location of the [Status] column
        int index = lines[lines.Length - 2].IndexOf("Status");
    
        // Now replace the text under that Status Column in the next row
        // Remove the OK characters (first two)
        lines[lines.Length - 1] = lines[lines.Length - 1].Remove(index, 2);
        // Then Insert the two characters you want
        lines[lines.Length - 1] = lines[lines.Length - 1].Insert(index, "NG");
    }