在特定句子后写在文件中

Write in file after specific sentence

我想在找到特定句子后将一些数据添加到文本文件中,例如我想在找到后添加一些字符串 This the place to write your sentence
我该怎么做,我使用 StreamWriter .

正确写入文本文件

任何人都可以给我一些代码或 link 吗?

在文件中插入文本并不容易,因为您必须将数据移动到插入点之后才能为新文本腾出空间。 StreamWriter 不支持所需的文件操作。

简单的做法是将文件读入字符串,修改字符串后再写入文件:

string text = File.ReadAllText(fileName);
string insertPoint = "This the place to write your sentence";
int index = text.IndexOf(insertPoint) + insertPoint.Length;
text = text.Insert(index, "Text to insert");
File.WriteAllText(fileNAme, text);

使用File.ReadAllLines to read the entire text file into a string. Then to find the specific sentence "This the place to write your sentence" use the method String.IndexOf. Once you have the index you can use the method String.Insert to add whatever text you want. Finally overwrite the existing file with the new string you just created using File.WriteAllLines。如果您愿意,也可以使用 StreamWriter.WriteLine 方法。

它真的是关于 System.IO.Stream(实现 IDisposable,所以你应该在 using 语句中使用它),byte[](又名缓冲区)和 System.Text.ASCIIEncoding.ASCII 或更常用的 System.Text.UTF8encoding.UTF8 编码。


话虽如此,System.IO.File 上有一些静态方法可以让这个操作变得非常简单。

        System.Text.Encoding encoding = System.Text.UTF8Encoding.UTF8; // we don't have to declare and set a variable, I'm just doing this to emphasize the encoding class and it's usage.

        string myText = "My Text To Assert";
        string lookupText = "This the place to write your sentence";

        string filePath = "C:\test.txt";

        string payload = System.IO.File.ReadAllText(filePath, encoding);
        payload.Replace(lookupText, String.Format("{0}{1}", lookupText, myText));
        System.IO.File.WriteAllText(filePath, payload);