繁体   English   中英

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

[英]C# windows forms application:How can I replace a single line in a textfile without deleting the original file?

我正在制作一个使用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还是unstreamwriter吗?

如果您需要一种解决方案(代码golf :)),则可以使用

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

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

您不能只更改一行,而可以更改为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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM