Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

In c#, i am creating one excel file and storing in some location.After that ,i am sending an mail with that attachment then i am dispsing all the events using the below code

C#
SmtpServer.Send(mail);
                //mail.Attachments.Dispose();
                mail.Attachments.ToList().ForEach(a => a.Dispose());
                mail.Dispose();
                firstAttachment.Dispose();


Then I am trying to delete the file but it is throwing a IO exception error i.e. " The process cannot access the file because it is being used by another process."

Please help on this.

Thanks,
subba Reddy.
Posted
Comments
Andy Lanng 21-Aug-15 6:44am    
If you place the file in the %tmp% folder then it will be cleaned up soon after you dispose of it. Otherwise you can create a class that implements IDisposable and add code to delete the file there after you have disposed of the object reference.

It depends on why the file is in use. You may find that the SmtpServer.Send(mail); is async and is still sending when you try to delete it.
Tomas Takac 22-Aug-15 3:18am    
Dispose should do it. You are disposing the message but do it properly and enclose it in "using". That way you make sure there it get's disposed.
Does SmtpClient.Send with attachments included hold a lock on the attached file?[^]
SMTP Send is locking up my files - c#[^]
Preventing File Locking in E-mail Attachment[^]

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