CodeArtist
CodeArtist

Reputation: 5684

How to format text loaded from file?

I have a .htm file like template and i want to read the contents and update a specific part of the page. The file has a typical html format where in some point i added the special string {0} in order to be able to format it. Also i made sure that the {0} is the only one occurrence.

I've tried the following, but throws me an exception Input string was not in a correct format:

sText = @File.ReadAllText("template.htm"));
formated = string.Format(sText, "Add some additional text here");

Which would be the correct way to implement this?

Thanks

Edit

The contents of the variable (debug) start like this:

    "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head>\r\n    <title></title>\r\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n    <style type=\"text/css\">\r\nbody {\r\n  margin: 0;\r\n  mso-line-height-rule: exactly;\r\n  padding: 0;\r\n  min-width: 100%;\r\n}\r\ntable {\r\n  border-collapse: collapse;\r\n  border-spacing: 0;\r\n}\r\ntd {\r\n  padding: 0;\r\n  vertical-align: top;\r\n}\r\n.spacer,\r\n.border {\r\n  font-size: 1px;\r\n  line-height: 1px;\r\n}\r\n.spacer {\r\n  width: 100%;\r\n}\r\nimg {\r\n  border: 0;\r\n  -ms-interpolation-mode: bicubic;\r\n}\r\n.image {\r\n  font-size: 0;\r\n  Margin-bottom: 24px;\r\n}\r\n.image img {\r\n  display: block;\r\n}\r\n.logo {\r\n  mso-line-height-rule: at-least;\r\n}\r\n.logo img {\r\n  display: block;\r\n}\r\nstrong {\r\n  font-weight: 

Edit 2

For just in case for people searching something like this i actually found something called HTMLAgilityPack and looks exactly what i need!

Upvotes: 1

Views: 2198

Answers (1)

DrKoch
DrKoch

Reputation: 9772

The format string in string.Format() looks for many characters/patterns to do its work. It is (generally) very dangerous to use "arbitrary" text there. In your case a much better (safer) solution would be:

sText = @File.ReadAllText("template.htm"));
formated = sText.Replace("{0}", "Add some additional text here");

Upvotes: 5

Related Questions