views:

213

answers:

2

hi folks., 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

+1  A: 

You can't delete a attached file after sending the mail.Before sending you can delete.

What the error says that, the path you have mentioned is using some other process.

MailMessage Message = new MailMessage();

Message.Subject = "Attachment Test";
Message.Body = "Check out the attachment!";
Message.To.Add("[email protected]");
Message.From = "[email protected]";

Message.Attachments.Add(new Attachment(memorystream, "test.txt", MediaTypeNames.Application.Text));

Notice that we created the attachment from the MemoryStream and we got to name the attachment anything we want. The name of the attachment in the second parameter is the name of the file in the email, not the name on the local system hard drive. In fact the attachment never goes to the local hard drive. The third parameter is the Mime type of the attachment, in our case this is text.

Edit: use Dispose() the mail

anishmarokey
i think you need to dispose the attachment objects.
anishmarokey
+4  A: 

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.

DarkBobG
You should really post some code then, because the test I ran worked in the way that it should.
DarkBobG