C#Won';t更改文本文件中的行
本文关键字:文件 文本 C#Won | 更新日期: 2023-09-27 18:20:51
好吧,相信我,我已经到处研究过了,并向一些朋友询问了这个问题。但我的代码:http://pastebin.com/0JSA9MzA在那里。指定的两行之间的代码应该逐行检查文本文档中startLine变量指定的文本行,然后将所有内容从oldFont变量更改为newFont变量,然后在endLine变量处结束。但每当我运行它时,它都无法产生结果,也不会出现任何错误。
除非您告诉代码更改文件中的文本,否则您的代码不会更改该文件中的文字。您当前只修改读取的文本,但从未将其写回文件。
试试这个:
private void editText()
{
System.IO.StreamReader read = new System.IO.StreamReader(filePath);
//write to new file because it's not possible to replace text in existing file directly
System.IO.TextWriter writer = new System.IO.TextWriter(filePath+"_");
while ((line = read.ReadLine()) != null)
{
writer.WriteLine(line); //write unmodified line to new file
if (startLine == line)
{
while ((line = read.ReadLine()) != null)
{
if (line == endLine)
{
writer.WriteLine(line); //write unmodified line to new file
break; //exit cycle
}
else
{
line = line.Replace(oldFont, newFontS); //replace content in line
writer.WriteLine(line); //write modified line to new file
}
}
}
}
read.Close();
writer.Close();
System.IO.File.Delete(filePath); //delete old file
System.IO.File.Move(filePath+"_",filePath); //rename new file to original filename
MessageBox.Show("Done!");
}