c# - 在文本文件中加载和访问模板变量

标签 c# .net c#-4.0

我们有一堆文本模板,它们是我们 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/

相关文章:

c# - 在创建时调用 Lambda

c# - 从字符串中删除重复值

asp.net - Asp.net 4.0 中的安全和不安全页面

c# - 将参数传递给 EventHandler

c# - 当我从 Visual Studio 中运行我的程序时,为什么我的 ComboBox 需要很长时间才能下拉?

c# - MVC 错误 : The model item passed into the dictionary is null

c# - 在 StackExchange.Redis 中通过键模式获取值

c# - 条件foreach循环c#

c# - .NET 可移植类库和 UDP 支持

tsql - 是否可以将 DependentTransaction 或多个 DependentTransactions 与 TPL/Parallelism 一起使用?