我正在使用在ReadWrite模式下打开的streamreader读取文件。我的要求是检查特定文本的文件,如果找到,用新行替换该行。
目前我已初次化StreamWriter
进行写作。
它正在将文本写入文件,但它将其附加到新行。
那么我应该怎么做才能替换特定的行文字?
System.IO.FileStream oStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read);
System.IO.FileStream iStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
System.IO.StreamWriter sw = new System.IO.StreamWriter(oStream);
System.IO.StreamReader sr = new System.IO.StreamReader(iStream);
string line;
int counter = 0;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("line_found"))
{
sw.WriteLine("line_found false");
break;
}
counter++;
}
sw.Close();
sr.Close();
答案 0 :(得分:3)
嗨,请尝试下面的代码....它会帮助你......
//替换文本文件中的所有HI ...
var fileContents = System.IO.File.ReadAllText(@"C:\Sample.txt");
fileContents = fileContents.Replace("Hi","BYE");
System.IO.File.WriteAllText(@"C:\Sample.txt", fileContents);
//替换特定行中的HI ....
string[] lines = System.IO.File.ReadAllLines("Sample.txt");
for (int i = 0; i < lines.Length; i++)
{
if(lines[i].Contains("hi"))
{
MessageBox.Show("Found");
lines[i] = lines[i].Replace("hi", "BYE");
break;
}
}
System.IO.File.WriteAllLines("Sample.txt", lines);