We all use HTML templates while sending emails. And sometimes, we need to remove some content from that file at runtime, especially when we need to remove TR tag from table HTML by Id. Previously, it was a tedious task for me. But after a lot of Google search, finally I found the solution of how to remove specific TR tags from table by Id at runtime.
RemoveTrTag() Function
- public void RemoveTrTag()
- {
- var filePath = Server.MapPath("~/JobChunkEmailTemplate.html");
- StringBuilder sbMailTemplate = new StringBuilder();
- using (StreamReader reader = new StreamReader(filePath, Encoding.Default))
- {
- sbMailTemplate.Append(reader.ReadToEnd());
- }
- string pattern = "<tr id=\"GoogleAdwordsSectionId\".+?</tr>";
- Regex r = new Regex(pattern, RegexOptions.Singleline);
- string result = r.Replace(sbMailTemplate.ToString(), "");
- sbMailTemplate.Replace(sbMailTemplate.ToString(), result);
- }
Do not forget to add the below namespaces in your code.
- using System.IO;
- using System.Text;
- using System.Text.RegularExpressions;
HTML file Contents
- <body>
- <form id="form1">
- <table id="EmailTable" style="width:100%;border: 1px solid black;border-collapse: collapse;">
- <tr id="GASectionId" style="border-width:1px;border-style:solid;#GA#">
- <td style="width:10%;border: 1px solid black;">Account</td>
- <td style="width:15%;border: 1px solid black;">ProjectId</td>
- <td style="width:15%;border: 1px solid black;">Extraction Date</td>
- <td style="width:50%;border: 1px solid black;">Failure Reason</td>
- <td style="width:10%;border: 1px solid black;">Component</td>
- </tr>
- <tr id="GoogleAdwordsSectionId" style="border-width:1px;border-style:solid;#GoggleAds#">
- <td style="width:15%;border: 1px solid black;">CustomerId / AccountId</td>
- <td style="width:10%;border: 1px solid black;">LocationId</td>
- <td style="width:15%;border: 1px solid black;">Extraction Date</td>
- <td style="width:50%;border: 1px solid black;">Failure Reason</td>
- <td style="width:10%;border: 1px solid black;">Component</td>
- </tr>
- {Body}
- </table>
- </form>
- </body>
In my case, tr tag Id is GoogleAdwordsSectionId. Put the Id in reg expression and try with your example. You can also find a demo example in source code.