2

I am having html code in string variable. In that I have mutiple image tags and I want replace the src of image tag with new src.

I am using this code :

    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);
    }
2
  • 7
    and what the problem? Commented Aug 10, 2015 at 4:38
  • Replace doesn't change the string, it returns an updated string instead. So you need to assign it back to emailbody. Commented Aug 10, 2015 at 6:58

1 Answer 1

3

You can use HtmlAgilityPack to parse and replace tags inner html and images sources.

Edit: Example: to replace 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);
     }
}
Sign up to request clarification or add additional context in comments.

2 Comments

HtmlAgilityPack is nice, but I'd also recommend looking at CsQuery
Thanx for your answer .My code is also working .i was doing mistake, i was note updating variable thats why i was not abel to get updates

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.