James Jeffery
James Jeffery

Reputation: 109

Constructing a string from a large chunk of HTML

Just wondering if there is an easy way around my issue. If I want to place a large chunk of HTML into a string, how's it possible without escaping the HTML first? There is so much HTML which is used for my MySpace bot (inserting into profiles) that it will take forever to escape.

Upvotes: 1

Views: 217

Answers (4)

lc.
lc.

Reputation: 116438

Following what @MattMitchell suggested, you can include the file as a resource in your project. Then you only have to reference it (MyNameSpace.Properties.Resources.MyHTMLFile) to get the contents as a string.

Upvotes: 3

Matt Mitchell
Matt Mitchell

Reputation: 41823

Put it in a file, load the file.

Example:

string myHTML;
using (FileStream file = new FileStream("path.txt", FileMode, FileAccess))
{
    using (StreamReader sr = new StreamReader(file))
    {
        myHTML = sr.ReadToEnd();
        sr.Close();
    }
    file.Close();
}

If you want to insert variables into your HTML, replace the variable locations with {0} .. {n} and then use string.Format();

E.g.

<html><div>{0} = {1}</div></html>

and in your C#

string myHTMLwithVars = string.Format(myHTML, var1, var2);

Alternatively (and more manageable if there are lots of variables or the order is likely to change), name each "variable spot" in your HTML and use string replace.

<html><div>{username} = {randomImageFile}</div></html>

c# change:

string myHTMLwithVars = myHTML
    .Replace("{username}", usernameVar)
    .Replace("{randomImageFile}", "image.jpg");

Upvotes: 2

Alex
Alex

Reputation: 14618

Why not read this HTML from a file, or an embedded resource in your project? That way no escaping is necessary.

to read from file:

string contents = File.ReadAllText("path/to/file.htm");

Upvotes: 0

David M
David M

Reputation: 72840

It isn't. But you can use a verbatim string literal (prefixed with @) to make your life slightly easier - you'd only have to replace " with "" to escape the string.

Upvotes: 2

Related Questions