小编Lui*_*uis的帖子

在C#中编辑文本文件的特定行

我有两个文本文件,Source.txt和Target.txt.源将永远不会被修改并包含N行文本.所以,我想删除Target.txt中的特定文本行,并用Source.txt中的特定文本行替换,我知道我需要的行数,实际上是行号2,两个文件.

我有这样的事情:

string line = string.Empty;
int line_number = 1;
int line_to_edit = 2;

using (StreamReader reader = new StreamReader(@"C:\source.xml"))
{
    using (StreamWriter writer = new StreamWriter(@"C:\target.xml"))
    {
        while ((line = reader.ReadLine()) != null)
        {
            if (line_number == line_to_edit)
            {
                writer.WriteLine(line);
            } 

            line_number++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我打开Writer时,目标文件被擦除,它会写入行,但是,当打开时,目标文件只包含复制的行,其余的则丢失.

我能做什么?

c# stream filestream

29
推荐指数
2
解决办法
11万
查看次数

标签 统计

c# ×1

filestream ×1

stream ×1