如何格式化从文件加载的文本?

Cod*_*ist 1 c# file-io text string-formatting

我有一个.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");
Run Code Online (Sandbox Code Playgroud)

哪一个是实现这个的正确方法?

谢谢

编辑

变量(调试)的内容如下所示:

    "<!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: 
Run Code Online (Sandbox Code Playgroud)

编辑2

为了以防万一人们搜索这样的东西,我实际上找到了一个叫做HTMLAgilityPack的东西,看起来正是我需要的!

DrK*_*och 5

string.Format() 中的格式字符串会查找许多字符/模式来完成其工作。在那里使用“任意”文本(通常)是非常危险的。在您的情况下,更好(更安全)的解决方案是:

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