I got the following code
protected override void Render(HtmlTextWriter writer)
{
// Write the HTML into this string builder
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hWriter = new HtmlTextWriter(sw);
base.Render(hWriter);
string pageHTML = sb.ToString();
// Write it back to the server
writer.Write(pageHTML);
if (Convert.ToBoolean(this.ViewState["SendEmail"]))
{
string HTML = "";
HTML = "<!DOCTYPE HTML PUBLIC '-//IETF//DTD HTML//EN'>";
HTML += "<html>";
HTML += "<head>";
HTML += "<meta http-equiv='Content-Type'";
HTML += "content='text/html; charset=iso-8859-1'>";
HTML += "<title>Order Information</title>";
HTML += "</head>";
HTML += "<body>";
HTML += "See attachment for information.";
HTML += "</body>";
HTML += "</html>";
MailMessage mail = new MailMessage("from@xxx.com", "to@xxx.com", "Subject", HTML);
mail.IsBodyHtml = true;
string path = @"d:\websites\plate.html";
using (StreamWriter sw11 = File.CreateText(path))
{
sw11.WriteLine(pageHTML);
}
mail.Attachments.Add(new Attachment(path));
SmtpClient client = new SmtpClient("192.168.1.127");
client.Send( mail );
Response.Write("<script>alert('Your information has been sent.')</script>");
this.ViewState["SendEmail"] = false;
}
}
After a fresh clean/build of my solution, when I press the send button, this function is called and the html page is sent in attachment by mail without a problem. But if I try to press again the send button, I’m getting “System.IO.IOException: The process cannot access the file ‘d:\websites\plate.html’ because it is being used by another process.” The error occur when I’m trying to open the file. What’s wrong?
As Eric has pointed out, you should have the
SmtpClientin ausingstatement – dittoMailMessage.However, you’d still end up writing to the file system for no obvious reason. I’d strongly advise you to use one of the
Attachmentconstructors which doesn’t require a file to start with. You can write to aMemoryStream, rewind it, and then provide that to theAttachmentfor example.Aside from anything else, that would mean you wouldn’t have a problem if multiple threads (or processes) tried running this code at the same time.