Search code examples
c#.nethtmlembedded-resource

How to include HTML document in .NET application with variable fields?


I have a C#/.NET app which currently uses StringBuilder to generate an HTML email message.

A new message format has been developed and now includes more formatting and CSS. I'd like to avoid appending each line of the file using StringBuilder, so I thought it best to include the HTML file as a resource.

However, there are about 21 variables within the CSS and HTML which I need to change on the fly. My first thought was to replace them with the standard String.Format placeholders ({0}, {1} etc) but when viewing the HTML, validation complains about these.

I'm rather stumped as to what the best practice is for storing a 200-line HTML file and changing parts of it before inclusion in an email.

Example:

Within the CSS, I need to change the color of certain elements, like this:

#header
{
    background-color: {0};
}

And within the HTML, I need to change strings and URLs, like this:

<img src="{1}" />
<span>{2}</span>

It seems including the HTML as a resource in the project would be best, but trying to use String.Format with that resource, regardless if it would work, is a poor method because of the aforementioned validation errors.

Any suggestions?


Solution

  • Instead of using {1} use a name e.g. Table1HeaderImage, then instead of using String.Format use String.Replace. You could have a collection of thingies to put in thehtml then, a quick loop, even extra attributes for customisation from users version, etc.