我有一个类似模板的 .htm 文件,我想读取内容并更新页面的特定部分。 该文件具有典型的 html 格式,在某些时候我添加了特殊字符串 {0} 以便能够对其进行格式化。我还确保 {0} 是唯一一次出现。
我试过以下方法,但抛出异常 Input string was not in a correct format:
sText = @File.ReadAllText("template.htm"));
formated = string.Format(sText, "Add some additional text here");
哪种方法才是正确的实现方式?
谢谢
编辑
变量(debug)的内容是这样开始的:
"<!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:
编辑2
为了以防万一人们搜索这样的东西,我实际上找到了一个叫做 HTMLAgilityPack 的东西看起来正是我需要的!
请您参考如下方法:
string.Format() 中的格式字符串寻找许多字符/模式来完成它的工作。在那里使用“任意”文本(通常)是非常危险的。 在您的情况下,更好(更安全)的解决方案是:
sText = @File.ReadAllText("template.htm"));
formated = sText.Replace("{0}", "Add some additional text here");
