Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete attachment file

i am using System.Net.Mail for sending mail in asp.net.. how to delete attachment file after it is send as attachment mail.. i tried to use File.Delete method.. but i am getting this error.. the process cannot access the file path\fun.jpg' because it is being used by another process. thank you

like image 312
SAK Avatar asked May 18 '10 12:05

SAK


People also ask

How do I delete attachments from a PDF?

If the file is attached as an embedded file, go to the attachments tab where the list of attached files is displayed, right-click (Mac: Ctrl+Click) on the attached file and choose the option Delete.

How do I remove an attachment from my phone?

Open your phone's Files app . Tap a file. Delete .

How do I delete shared attachments?

Tap on the contact icon and select Info. Scroll down to see the attachments the contact has sent you. Tap See All and select the ones you want to delete. When you are done, tap Delete.


1 Answers

Dispose of the MailMessage when you're done with it. It still has a lock on the file you've added as an attachment until you've done so.

var filePath = "C:\\path\\to\\file.txt";
var smtpClient = new SmtpClient("mailhost");
using (var message = new MailMessage())
{
    message.To.Add("[email protected]");
    message.From = new MailAddress("[email protected]");
    message.Subject = "Test";
    message.SubjectEncoding = Encoding.UTF8;
    message.Body = "Test " + DateTime.Now;
    message.Attachments.Add(new Attachment(filePath));
}
if (File.Exists(filePath)) File.Delete(filePath);
Console.WriteLine(File.Exists(filePath));

Output: False

I would imagine that if you still have something locking the file after disposing the message, that you likely have another lock on the file, but without code, we can't help you.

like image 52
Bob G Avatar answered Oct 13 '22 22:10

Bob G