C#windows窗体应用程序:如何在不删除原始文件的情况下替换文本文件中的单行?

时间:2013-01-24 04:23:18

标签: c# windows forms streamwriter

我正在制作一个使用streamreader和streamwriter的项目,是否有可能只更换或保存特定行中的文本而不影响其他行? 如果我这样做

streamreader sr = new streamreader(@"txtfile");
list<string> lines = new list<string>();
while (!sr.EndOfStream)
sr.readline();
{
     lines.Add(sr.ReadLine();
}

//put in textbox
sr.close();

{
streamwriter sw = new streamwriter(@"txtfile");
sw.WriteLine(textBox1.text);
sw.close();
}

这只是一个示例,但我是否有可能使用list而非streamwriter?

3 个答案:

答案 0 :(得分:1)

如果您想要一个单行解决方案(代码高尔夫:)),您可以使用

string path = @"C:\Test.txt";
string lineToReplace = "Relpace This Line";
string newLineValue = "I Replaced This Line";

File.WriteAllLines(path, File.ReadAllLines(path).Select(line => line.Equals(lineToReplace) ? newLineValue : line));

答案 1 :(得分:0)

将文件读入内存,更改要更改的行,关闭阅读器,打开文件进行写入,写出文件的新内容。

答案 2 :(得分:0)

你不能只改变一条线,但你可以 ReadAllLines 找到你要改变的行更改它并将所有内容写入该文件再次

StringBuilder newFile = new StringBuilder();
string temp = "";
string[] file = File.ReadAllLines(@"txtfile");

foreach (string line in file)
{
    if (line.Contains("string you want to replace"))
    {
        temp = line.Replace("string you want to replace", "New String");
        newFile.Append(temp + "\r\n");
        continue;
    }
    newFile.Append(line + "\r\n");
}

File.WriteAllText(@"txtfile", newFile.ToString());