你不能在不重写整个文件的情况下重写一行(除非这些行恰好是相同的长度)。如果您的文件很小,那么将整个目标文件读入内存然后再次将其写出可能是有意义的。你可以这样做:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2; // Warning: 1-based indexing!
string sourceFile = "source.txt";
string destinationFile = "target.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read the old file.
string[] lines = File.ReadAllLines(destinationFile);
// Write the new file over the old file.
using (StreamWriter writer = new StreamWriter(destinationFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(lines[currentLine - 1]);
}
}
}
}
}
如果您的文件很大,最好创建一个新文件,这样您就可以在写入另一个文件时从一个文件读取流。这意味着您不需要一次将整个文件保存在内存中。你可以这样做:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2;
string sourceFile = "source.txt";
string destinationFile = "target.txt";
string tempFile = "target2.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read from the target file and write to a new file.
int line_number = 1;
string line = null;
using (StreamReader reader = new StreamReader(destinationFile))
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(line);
}
line_number++;
}
}
// TODO: Delete the old file and replace it with the new file here.
}
}
一旦确定写入操作成功(没有抛出异常并且写入器已关闭),您就可以稍后移动文件。
请注意,在这两种情况下,对行号使用基于 1 的索引有点令人困惑。在您的代码中使用基于 0 的索引可能更有意义。如果您愿意,您可以在程序的用户界面中使用基于 1 的索引,但在进一步发送之前将其转换为 0 索引。
此外,直接用新文件覆盖旧文件的一个缺点是,如果它在中途失败,那么您可能会永久丢失任何未写入的数据。通过首先写入第三个文件,您只有在确定有另一个(更正的)副本后才删除原始数据,因此如果计算机中途崩溃,您可以恢复数据。
最后一点:我注意到您的文件具有 xml 扩展名。您可能需要考虑使用 XML 解析器来修改文件内容而不是替换特定行是否更有意义。