[英]How to use String.Replace method for html string
我在字符串變量中有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);
}
您可以使用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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.