C# 写入时重写文件中的行

C# 写入时重写文件中的行,c#,C#,我正在使用以读写模式打开的streamreader读取文件。我的要求是检查文件中的特定文本,如果找到了,就用新行替换该行 目前,我已经初始化了一个StreamWriter来进行编写 它将文本写入文件,但将其追加到新行 那么,我应该如何替换特定的行文本呢 System.IO.FileStream oStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, S

我正在使用以读写模式打开的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();

您好,请尝试下面的代码。。。。它将帮助你

//替换文本文件中的所有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);
string[]lines=System.IO.File.ReadAllLines(“Sample.txt”);
对于(int i=0;i
您好,请尝试以下代码。。。。它将帮助你

//替换文本文件中的所有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);
string[]lines=System.IO.File.ReadAllLines(“Sample.txt”);
对于(int i=0;i
请将您的代码粘贴到问题中。请将您的代码粘贴到问题中。它会将所有与“Hi”匹配的内容替换为“BYE”,我的要求是替换特定行的文本。可能吗?它会将所有与“Hi”匹配的内容替换为“BYE”,我的要求是替换特定行的文本。可能吗?