I want to delete the image after sending the image by email. But I get one exception as follows:
The process cannot access the file 'C:\Users\LTP-Dell-72\source\repos\Demo2\Demo2\Images\Koala.jpg' because it is being used by another process.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Net.Mail;
- using System.IO;
- using System.Text;
- using System.Net.Mime;
- namespace Demo2
- {
- public partial class Email : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void btn_send_Click(object sender, EventArgs e)
- {
- try
- {
- MailMessage message = new MailMessage();
- message.To.Add(txtEmail.Text);
- message.Subject = txtSubject.Text;
- message.From = new
- System.Net.Mail.MailAddress("****");
- message.IsBodyHtml = true;
- message.AlternateViews.Add(Mail_Body());
- SmtpClient SmtpMail = new SmtpClient();
- SmtpMail.Host = "smtp.gmail.com";
- SmtpMail.Port = 587;
- SmtpMail.Credentials = new
- System.Net.NetworkCredential("****","****");
- SmtpMail.DeliveryMethod = SmtpDeliveryMethod.Network;
- SmtpMail.EnableSsl = true;
- SmtpMail.ServicePoint.MaxIdleTime = 0;
- SmtpMail.ServicePoint.SetTcpKeepAlive(true, 2000, 2000);
- message.BodyEncoding = Encoding.Default;
- message.Priority = MailPriority.High;
- SmtpMail.Send(message);
-
- message.Dispose();
- String FileName = fileUpload1.PostedFile.FileName;
- string path1 = Server.MapPath("~/Images/");
- string path = path1 + FileName;
-
-
-
- File.Delete(path);
-
- Response.Write("Email has been sent");
- }
- catch (Exception ex)
- { Response.Write("Failed"); }
- }
- private AlternateView Mail_Body()
- {
- String FileName = fileUpload1.PostedFile.FileName;
- string path1 = Server.MapPath("~/Images/");
- string path = path1 + FileName;
- LinkedResource Img = new LinkedResource(path, MediaTypeNames.Image.Jpeg);
- Img.ContentId = "MyImage";
- string str = @"
- <table>
- <tr>
- <td> '" + txtmessagebody.Text + @"'
- </td>
- </tr>
- <tr>
- <td>
- <img src=cid:MyImage id='img' alt='' width='100px' height='100px'/>
- </td>
- </tr></table>
- ";
- AlternateView AV =
- AlternateView.CreateAlternateViewFromString(str, null, MediaTypeNames.Text.Html);
- AV.LinkedResources.Add(Img);
- return AV;
- }
- }
- }