如何有效地删除文件中的最后一行并为大文件附加新文本?



替换文件中最后一行的有效方法是什么?

我希望我的文件以"]"结尾,我想用新数据替换"]",这些数据将再次以"]"结尾。

这只是一个文件非常大的示例......

Old:
[
a
b
c
]

新增功能:

[
a
b
c
d
e
]

我可以完全控制文件的编写和创建方式。

编辑:

// mockData.json
//[
//    a
//    b
//    c
//]
var fileName = "mockData.json";
var origData = File.ReadAllLines(fileName);
origData[origData.Length - 1] = " dn en]";
File.WriteAllLines(fileName, origData);

对于下面的代码,例程非常简单,因为您已经知道文件中的最后一个字符是 ]。因此,您所要做的就是读取文件的最后一个字符,如果是 char ],那么您得到了该文件。如果发生这种情况,则截断文件中的最后一个字节,并将文本追加到该文件。然后添加 char ] 以保留格式。请注意,这是针对 ASCII 编码的,如果您的最后一个字符是大于一个字节的其他字符,那么您必须稍微修复代码。

using System;
using System.IO;
using System.Text;
public class FSSeek
{
public static void Main()
{
string fileName = "test.txt";
char lastChar = ']';
string toBeAppend = "dnen";
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
{
fs.Seek(-1, SeekOrigin.End);
if ( Convert.ToChar(fs.ReadByte()) == lastChar ){
fs.SetLength(fs.Length - 1);
fs.Write(Encoding.ASCII.GetBytes(toBeAppend));
fs.WriteByte(Convert.ToByte(lastChar));
}            
}
}
}

测试.txt内容:

[
a
b
c
]

我的建议是这样的:

读取文件,删除内容的最后一个字符,然后再次将其写入文件。

string fileContent = File.ReadAllText("file.path");
// Remove the last character
fileContent = fileContent.Remove(fileContent.Length - 1);
string newContent = "Your new content";
fileContent += newContent;
// Write content back to the file
File.WriteAllText("file.path", fileContent);

您可以像这样InsertRange()将范围插入列表,lines.Count - 1将确保您在最后一行之前插入。

var linesToAdd = new List<string>() { "d", "e" };
var lines = File.ReadAllLines(path).ToList();
lines.InsertRange(lines.Count - 1, linesToAdd);
File.WriteAllLines(path, lines);

显然,这需要错误处理,例如您的原始文件最后没有]

相关内容

最新更新