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

本文关键字:加载 文本 文件 格式化 | 更新日期: 2023-09-27 18:34:30

我有一个像模板这样的.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");

哪种是正确的实现方式?

谢谢

编辑

变量(调试(的内容开始如下:

    "<!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 的东西,看起来正是我需要的!

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

字符串

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

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