16

I need to store HTML code for an email template in a variable, so I want to load raw HTML source into a string. This obviously doesn't work if I can't escape its contents.

For instance, I can't do this:

string myHtml = "<html><body>
    <a href="foo.bar" class="blap">blip</a>
</body></html>";

How can I store HTML code as a native C# string?

7
  • where are you sending HTML code? how are you sending it? please clarify what you're trying to do Commented Oct 11, 2010 at 3:15
  • what are you trying to do? parse HTML in a HttpWebResponse? Commented Oct 11, 2010 at 3:15
  • I just want to send html email, so I use a string to store the email contents Commented Oct 11, 2010 at 3:17
  • Adding characters to a string should be a piece of cake (it's what strings are for). How does it "obviously" not work? What's happening that's causing it to fail? Commented Oct 11, 2010 at 3:20
  • 2
    Phew, it's a serious question. Here I was afraid it was going to be a knock-knock joke. Commented Oct 11, 2010 at 3:25

3 Answers 3

35

Strings and HTML should be fine. The only complication is escaping, which is made easier using verbatim string literals (@"..."). Then you just double any double-quotes:

string body = @"<html><body>
<a href=""foo.bar"" class=""blap"">blip</a>
...
</body></html>";
Sign up to request clarification or add additional context in comments.

5 Comments

So @"" is called a verbatim string literal? I'm gonna upvote because up until now I've been saying use an @(at) sign before the quotes. Thank you @Marc.
@marko - yes, that is the official name. Yours works too, though ;)
I'm not sure, but it just not working with my HTML coding, cos I've tried this, while the double quote still can't be properly interpreted . Could you try a more complex block of html? Like a whole page? Because the small block works on my computer either.
@user469652 - I think you need to find an example that doesn't work. As HTML is fine, honestly. If is doesn't work, you've either missed the @ or a "
Also we need to add double the number of brackets as well. In my case for {{userName}} it should be {{{{userName}}}}
7

If you html code is in a file you can File.ReadAllText

string myString = System.IO.File.ReadAllText("path to the file");

Comments

0

Old, but C# now also has a Raw String Literal feature to make this even easier:

string myHtml = """<html><body>
    <a href="foo.bar" class="blap">blip</a>
</body></html>""";

No need to worry about the quotes in the string, and you can use any number of starting/ending quotes if for some reason you have text already containing sets of quotes together.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.