实现这一目标的一个策略是创建一个html模板......
$$TEXT1$$
$$TEXT2$$
此模板已使用诸如$$ TEXT1 $$之类的标记进行检测。这些将在以后用自定义文本替换。
将模板包含为资源,或作为外部文件或任何位置。我选择将其作为嵌入式资源包含在内。这是设置......
您要使用嵌入式资源,您也可以使用WebBrowser获取html。我喜欢使用资源,因为它避免了文件丢失或损坏导致的异常。
下一步很简单。这是一个有效的视图模型...
public class ViewModel
{
public string Text1 { get; set; }
public string Text2 { get; set; }
public string ImagePath { get; set; }
public string DestinationName { get; set; }
public void Start()
{
var resourceName = Assembly.GetExecutingAssembly().GetManifestResourceNames().Where(q => q.Contains("Template.html")).FirstOrDefault();
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
string html = reader.ReadToEnd().Replace("$$TEXT1$$", Text1).Replace("$$TEXT2$$", Text2).Replace("$$IMAGELOCATION$$", ImagePath);
File.WriteAllText(DestinationName, html);
}
}
}
}
View Model获取调用者设置的各种Text1(etc)属性,然后加载HTML模板并用自定义内容替换标记。然后它使用File上的静态方法来保存它。
您可以修改此策略以使用任何其他类型的工具,只要它一致。对于更具伸缩性,更全面的解决方案,我建议HtmlAgility。我已经使用它多年了。