将文本文件中的多个字符串替换为不同的文本

nag*_*508 1 c# streamreader

我有一个像这样的文本文件:

模板.txt

hello my name is [MYNAME], and i am of age [AGE].
i live in [COUNTRY].
i love to eat [FOOD]
Run Code Online (Sandbox Code Playgroud)

我试图用列表示例中的字符串替换方括号中的内容

//         // name //country // age // food           
p.Add(new Person("jack", "NZ", "20", "Prawns"));
p.Add(new Person("ana", "AUS", "23", "Chicken"));
p.Add(new Person("tom", "USA", "30", "Lamb"));
p.Add(new Person("ken", "JAPAN", "15", "Candy"));
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试了以下在循环内调用的函数

//loop
 static void Main(string[] args)
{
   int count = 0;
  foreach (var l in p)
  {
    FindAndReplace("template.txt","output"+count+".txt" ,"[MYNAME]",l.name);
    FindAndReplace("template.txt","output"+count+".txt" ,"[COUNTRY]",l.country);
    FindAndReplace("template.txt","output"+count+".txt" ,"[AGE]",l.age);
    FindAndReplace("template.txt","output"+count+".txt" ,"[FOOD]",l.food);
    count++;
  }
}
//find and replace function
 private static void FindAndReplace(string template_path,string save_path,string find,string replace)
        {           
            using (var sourceFile = File.OpenText(template_path))
            {
                // Open a stream for the temporary file
                using (var tempFileStream = new StreamWriter(save_path))
                {
                    string line;
                    // read lines while the file has them
                    while ((line = sourceFile.ReadLine()) != null)
                    {
                        // Do the word replacement
                        line = line.Replace(find, replace);
                        // Write the modified line to the new file
                        tempFileStream.WriteLine(line);
                    }
                }
            }
  
        }
Run Code Online (Sandbox Code Playgroud)

这就是我所做的。但我得到的输出是这样的

输出1.txt

hello my name is [MYNAME], and i am of age [AGE].
i live in [COUNTRY].
i love to eat Prawns
Run Code Online (Sandbox Code Playgroud)

输出2.txt

hello my name is [MYNAME], and i am of age [AGE].
i live in [COUNTRY].
i love to eat Chicken
Run Code Online (Sandbox Code Playgroud)

仅替换最后一个文本。

Con*_*oop 5

每次调用时FindAndReplace都会覆盖最后写入的文件。

当您第一次调用它时,它会读取模板文件,[MYNAME]用一个值替换特定占位符 ( ) 并将其写入新文件。在下一次调用中,您再次使用模板,因此[MYNAME]不再替换,仅替换国家/地区并将其写入同一文件并覆盖内容。如此重复,直到您接到最后一个电话。

这就是为什么只有[FOOD]被替换。尝试一次性替换所有文本,然后将其写入文件。