Can't delete file after sending it attached to a mail message

S

Seguros Catatumbo

Hi guys, i am having trouble deleting a file after sending an email.
The file is in use.

Here's the code:


String texto = "Test";
System.Net.Mail.SmtpClient smtp = new
System.Net.Mail.SmtpClient();
System.Net.Mail.MailMessage correo = new
System.Net.Mail.MailMessage();
correo.To.Add("(e-mail address removed)");
correo.Body = texto;
correo.IsBodyHtml = false;
string pdf="file.pdf";
correo.Attachments.Add(new
System.Net.Mail.Attachment(Server.MapPath(pdf)));
try
{
smtp.Send(correo);
}
catch (Exception)
{
}
finally{
File.Delete(pdf);
}

I have searched on the web and everyone seems to be doing it the same
way. I dont know if this is relevant, but i am creating that file from
itextsharp, a port of itext to c#, which reads a pdf form and saves it
to a new file, which is the one being attached. The pdf file (called a
"stamper") is being closed before the redirect to the email page
happens. And the email is sent succesfully with the attached file if i
don't delete it.
 
L

Lit

As a test can you delete the file before you send it?
why not null or destroy correo.
Lit
 
A

Alexey Smirnov

Hi guys, i am having trouble deleting a file after sending an email.
The file is in use.

Here's the code:

String texto = "Test";
System.Net.Mail.SmtpClient smtp = new
System.Net.Mail.SmtpClient();
System.Net.Mail.MailMessage correo = new
System.Net.Mail.MailMessage();
correo.To.Add("(e-mail address removed)");
correo.Body = texto;
correo.IsBodyHtml = false;
string pdf="file.pdf";
correo.Attachments.Add(new
System.Net.Mail.Attachment(Server.MapPath(pdf)));
try
{
smtp.Send(correo);
}
catch (Exception)
{
}
finally{
File.Delete(pdf);
}

I have searched on the web and everyone seems to be doing it the same
way. I dont know if this is relevant, but i am creating that file from
itextsharp, a port of itext to c#, which reads a pdf form and saves it
to a new file, which is the one being attached. The pdf file (called a
"stamper") is being closed before the redirect to the email page
happens. And the email is sent succesfully with the attached file if i
don't delete it.

You need to dispose all Attachment objects, or you will leave open
file handles behind. Calling Dispose on the MailMessage will trigger
dispose calls in any attachments it contains.

smtp.Send(correo);
correo.Dispose();
 
S

Seguros Catatumbo

You need to dispose all Attachment objects, or you will leave open
file handles behind. Calling Dispose on the MailMessage will trigger
dispose calls in any attachments it contains.

smtp.Send(correo);
correo.Dispose();

I was just going to reply that i found out about correo.Dispose() and
that it worked :)

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top