我在字符串变量中使用html代码。因为我有多个图像标签,我想用新的src替换图像标签的src。
我正在使用此代码:
foreach (MessagePart attchment in unseenMessage.FindAllAttachments())
{
attchments = Guid.NewGuid().ToString() + attchment.FileName;
string src="cid:"+ attchment.ContentId;
string newsrc = "/Attachment/" + attchments;
emailbody.Replace(src, newsrc);
string filepath = "D:\\AceoCRM\\Aceo.Web\\Attachment\\" + attchments;
using (FileStream fs = new FileStream(filepath, FileMode.CreateNew))
{
fs.Write(attchment.Body, 0, attchment.Body.Length);
fs.Close();
}
listOfAttachments.Add(attchments);
}
答案 0 :(得分:3)
您可以使用HtmlAgilityPack来解析和替换内部html和图片来源的标签。
编辑: 示例:替换src
var documnet = new HtmlDocument();
documnet.LoadHtml("HtmlString");
foreach (var href in documnet.DocumentNode.Descendants("img").Where(href => !href.OuterHtml.Trim().Contains("http")))
{
try
{
//here image src URL being changed...
href.Attributes["src"].Value = href.Attributes["src"].Value.Trim().StartsWith("//") ? String.Format("http:{0}", href.Attributes["src"].Value.Trim()) : String.Format("{0}/{1}", baseUrl, href.Attributes["src"].Value.TrimFromStart("//"));
href.Attributes["srcset"].Value = href.Attributes["srcset"].Value.Trim().StartsWith("//") ? String.Format("http:{0}", href.Attributes["srcset"].Value.Trim()) : String.Format("{0}/{1}", baseUrl, href.Attributes["srcset"].Value.TrimFromStart("//"));
}
catch (NullReferenceException ex)
{
Log(ex);
}
}