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



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

template.txt

hello my name is [MYNAME], and i am of age [AGE].
i live in [COUNTRY].
i love to eat [FOOD]

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

//         // 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"));

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

//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);
}
}
}

}

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

输出1.txt

hello my name is [MYNAME], and i am of age [AGE].
i live in [COUNTRY].
i love to eat Prawns

输出2.txt

hello my name is [MYNAME], and i am of age [AGE].
i live in [COUNTRY].
i love to eat Chicken

只替换最后一个文本。

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

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

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

不要使用函数,而是尝试执行类似的操作

static void Main(string[] args)
{
int count = 0;
foreach (var l in p)
{                  
using (var sourceFile = File.OpenText("template.txt"))
{
// Open a stream for the temporary file
using (var tempFileStream = new StreamWriter("output" + count + ".txt"))
{
string line;
// read lines while the file has them
while ((line = sourceFile.ReadLine()) != null)
{

line = line.Replace("[MYNAME]", l.name);
line = line.Replace("[COUNTRY]", l.country);
line = line.Replace("[AGE]", l.age);
line = line.Replace("[FOOD]", l.food);
tempFileStream.WriteLine(line);
}// end of while loop
}
count++;
}//end foreach loop                             
}
}//end of main

最新更新