Click here to Skip to main content
15,888,020 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using C# .net code for sending mail with attachments.

mail has been successfully send but when i try to delete that attachment from the web folder the error is 550! the file is used by another process.

can you help me what should i do.
::code::

MailMessage mail;
SmtpClient objsmtp;

try
{
string FileName = Server.MapPath("~//EmailTemp.htm");
string FileContents;
System.IO.StreamReader myStreamReader;

if ((FileName != null))
{
myStreamReader = System.IO.File.OpenText(FileName);
FileContents = myStreamReader.ReadToEnd();
FileContents = FileContents.Replace("%Name%", tbxName.Text);
FileContents = FileContents.Replace("%Email%", tbxEmail.Text);
FileContents = FileContents.Replace("%Country%", tbxCountry.Text);
FileContents = FileContents.Replace("%Patients Testimonials%", tbxPatTestimonials.Text);



mail = new MailMessage();
String email = "email@yahoo.in";
mail.To.Add(tbxEmail.Text);
mail.Bcc.Add(email);
mail.From = new MailAddress("email@domainname.com");
string attach1 = null;

string strFileName = null;
if (fudReports .FileName != null)
{
// Get a reference to PostedFile object

// Get the file name
strFileName = Path.GetFileName(fudReports.FileName);
// Preced the file name with "attachments/" so
// the file is saved to our attachments directory
strFileName = "attachments/" + strFileName;
// Save the file on the server
fudReports.SaveAs(Server.MapPath(strFileName));
// Create the email attachment with the uploaded file
Attachment attach = new Attachment(Server.MapPath(strFileName));

// Attach the newly created email attachment
mail.Attachments.Add(attach);
// Store filename so we can delete it later
attach1 = strFileName;

}





mail.Subject = "Enquiry Mail";
mail.Body = FileContents.ToString();


mail.Priority = MailPriority.High;
mail.IsBodyHtml = true;
objsmtp = new SmtpClient();


objsmtp.Host = "hoshing server name";
objsmtp.UseDefaultCredentials = true;

objsmtp.Credentials = new System.Net.NetworkCredential("email@domianname.com", "Password");
objsmtp.DeliveryMethod = SmtpDeliveryMethod.Network;


objsmtp.Send(mail);
myStreamReader.Dispose();
FileName = null;

FileContents = null;
if (attach1 != null)
File.Delete(Server.MapPath(strFileName));

attach1 = null;

}
}
catch (Exception ex)
{
//divMess.InnerText = ex.Message;
}
finally
{
mail = null;
objsmtp = null;


}
Posted

1 solution

Rather than pass in the file to the Attachment constructor (which appears to be locking the file), I'd open it using a FileStream and pass the stream into the attachment. Make sure that you Close the FileStream before you call Delete on the file.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900