我们有一堆文本模板,它们是我们 visual studio 解决方案中的嵌入式资源。
我正在使用像这样的简单方法来加载它们:
public string getTemplate()
{
var assembly = Assembly.GetExecutingAssembly();
var templateName = "ResearchRequestTemplate.txt";
string result;
using (Stream stream = assembly.GetManifestResourceStream(templateName))
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
return result;
}
所以我可以使用上述方法加载文件,但是如何用我在代码中创建的变量替换文件中的模板变量?这可能吗?也许我做错了......
ResearchRequestTemplate.txt:
Hello { FellowDisplayName }
You have requested access to the { ResearchProjectTitle } Project.
Please submit all paperwork and badge ID to { ResourceManagerDisplayName }
谢谢!
最佳答案
您可以使用一系列 string.Replace()
语句。
或者您可以修改模板并使用string.Format
:
Hello {0}
You have requested access to the {1} Project.
Please submit all paperwork and badge ID to {2}
读入模板后,插入正确的值:
return string.Format(
result, fellowDisplayName, researchProjectTitle, resourceManagerDisplayName);
如果模板经常更改,并且有人没有仔细确保模板中的编号与传入参数的顺序相匹配,这可能有点容易出错。
关于c# - 在文本文件中加载和访问模板变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33111819/