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);// Email-ID of Receiver
- message.Subject = txtSubject.Text;// Subject of Email
- message.From = new
- System.Net.Mail.MailAddress("****");// Email-ID of Sender
- message.IsBodyHtml = true;
- message.AlternateViews.Add(Mail_Body());
- SmtpClient SmtpMail = new SmtpClient();
- SmtpMail.Host = "smtp.gmail.com";//name or IP-Address of Host used for SMTP transactions
- SmtpMail.Port = 587;//Port for sending the mail
- SmtpMail.Credentials = new
- System.Net.NetworkCredential("****","****");//username/password of network, if apply
- 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); //Smtpclient to send the mail message
- //message = null;
- message.Dispose();
- String FileName = fileUpload1.PostedFile.FileName;
- string path1 = Server.MapPath("~/Images/");
- string path = path1 + FileName;
- //FileInfo TheFile = new FileInfo(path);
- //if (TheFile.Exists)
- //{
- File.Delete(path); // It not works if file is used in another proces
- //}
- 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 = @"
'" + txtmessagebody.Text + @"' 'img' alt='' width='100px' height='100px'/>
- ";
- AlternateView AV =
- AlternateView.CreateAlternateViewFromString(str, null, MediaTypeNames.Text.Html);
- AV.LinkedResources.Add(Img);
- return AV;
- }
- }
- }
Rijwan AnsariPosted Apr 16, 2021, 2:46 PM
Salman BegPosted Apr 16, 2021, 12:34 PM