Question : How can I get an email to release its hold on an attachment after sending?

I am using a System.Net.Mail.MailMessage to send email messages with attachments - that all works fine. However, after the mail has been sent the attached item is still marked as in use and therefore a temporary file created specifically for the attachment cannot be deleted - the error message 'File is in use by another process' is displayed when the system attempts to remove it.

How can I ensure that the lock is released once the message has been sent?

Chris Bray
1:
2:
3:
4:
5:
6:
7:
8:
9:
// Add any attachments
                if (attachmentsListView.Items.Count > 0)
                {
                    foreach (ListViewItem AttachmentItem in attachmentsListView.Items)
                    {
                        Attachment attach = new Attachment(AttachmentItem.Tag.ToString());
                        message.Attachments.Add(attach);
                    }
                }

Answer : How can I get an email to release its hold on an attachment after sending?


I think in your code you are disposing the message; not individual attachment objects...try the change below :

private void EmailDialog_FormClosing(object sender, FormClosingEventArgs e)
        {

foreach (Attachment a in message.Attachments)
    a.Dispose();

            message.Attachments.Clear();
            message.Dispose();
            message = null;
            if (iconImageList != null)
                iconImageList.Dispose();
        }
Random Solutions  
 
programming4us programming4us