SkyeBoniwell SkyeBoniwell - 1 year ago 87
C# Question

Loading and accessing template variables inside text file

we have a bunch of text templates that are embedded resources in our visual studio solution.

I'm using a simple method like this to load them:

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;

So I can load the file with the above method, but how do I replace the template variables inside the file with variables I've created in my code? Is that even possible? Maybe I'm going about this all wrong...


Hello { FellowDisplayName }

You have requested access to the { ResearchProjectTitle } Project.

Please submit all paperwork and badge ID to { ResourceManagerDisplayName }


Answer Source

You could use a series of string.Replace() statements.

Or you could modify the template and make use of string.Format:

Hello {0}

You have requested access to the {1} Project.

    Please submit all paperwork and badge ID to {2}

After you read in the template, insert the correct values:

return string.Format(
    result, fellowDisplayName, researchProjectTitle, resourceManagerDisplayName);

This could be a bit error prone if the template changes often, and someone's not being careful to make sure the numbering in the template matches the order of parameters being passed in.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download