C# 如何在读取文件的同时修改文件?

C# 如何在读取文件的同时修改文件?,c#,file,C#,File,我想用c#编程,读取如下文件: System.IO.StreamWriter writer = new System.IO.StreamWriter(System.IO.File.Open(filename, System.IO.FileMode.Open)); writer.Write("cindy4"); writer.Flush(); 辛迪辛迪0辛迪1辛迪2辛迪3 苗苗苗苗1苗苗2苗苗3 我想在第一行末尾加上“cindy4”之类的词 System.IO.StreamReader fi

我想用c#编程,读取如下文件:

System.IO.StreamWriter writer = new System.IO.StreamWriter(System.IO.File.Open(filename, System.IO.FileMode.Open));
writer.Write("cindy4");
writer.Flush();

辛迪辛迪0辛迪1辛迪2辛迪3

苗苗苗苗1苗苗2苗苗3

我想在第一行末尾加上“cindy4”之类的词

System.IO.StreamReader file = new System.IO.StreamReader(filename);
string line = file.ReadLine();
while(line != null)
{
    if (line.Contains("cindy"))
    {
         tmp = line.Split(' ');
         file.Close();

         //TO DO change in the file

         break;
     }
     line = file.ReadLine();
}
在TODO部分,我的代码如下:

System.IO.StreamWriter writer = new System.IO.StreamWriter(System.IO.File.Open(filename, System.IO.FileMode.Open));
writer.Write("cindy4");
writer.Flush();
但它不起作用。谁能给我举个例子吗?

试试下面的代码:

string[] new_text = System.IO.File.ReadAllLines("file_path");
new_text[line_number] += "text_to_add"; 
//the line number start from zero 
//Example: first line will be: new_text[0]
//the second line will be: new_text[1]
//Etc...
System.IO.File.WriteAllLines("file_path",new_text);

“不起作用”是什么意思?错误?意外/错误行为?对于这样的任务,所有内容都必须读取和重新写入(有一些聪明的滑动窗口方法可以使用常量内存,但也可以先读取所有内容,然后再将其写出,因为这并不复杂,并且适用于像这样的琐碎情况)。没有“插入”文件操作。@Krumia我没有看到它在我的文件中写入“cindy4”。您的StreamReader可能锁定了该文件。确定你没有收到错误?@gunr217我没有收到错误,但它也没有在我的文件中写入任何内容。如果是的话,我想知道它是否处于正确的位置。所以我在这里提出这个问题。