开发者

IOException deleting files used attachments in MailMessage

i am using visual studios 2010 with .NET 4.0.

i am attaching files from my local hard drive to a MailMessage (i.e. MailMessage.Attachements.Add(Attachment)). after i execute the SmtpClient.Send(MailMessage) command, i iterate over the attachment paths and perform a File.开发者_C百科Delete(string path). however, i immediately get a System.IO.IOException.

System.IO.IOException: The process cannot access the file 'c:\temp\test.docx' because it is being used by another another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path) ...

i thought that maybe i couldn't delete large files because it was still being streamed during the SmtpClient.Send command. however, this seemingly happens for files of all sizes (2 KB to 8 MB). can someone please clarify what is going on?

is there a way to make sure the SmtpClient.Send call is complete (it has completely sent the email with the attachments and released all locks on the files/attachments) before i issue a File.Delete call?


You should ensure that the stream that the attachment stream is closed before you delete it.

I suggest wrapping the creation of the new attachment object in a using statement to ensure proper disposal before you try to delete the file.


File this under the better late than never category: I had the same issue, and was able to solve it by simply calling the Dispose() method on the MailMessage instance after sending the message, like so:

        try
        {
            MailMessage msg = new MailMessage();
            msg.To.Add(input.To);
            msg.From = new MailAddress(input.From);
            msg.Subject = input.Subject;
            msg.Body = input.Message;
            Attachment att = new Attachment(reportPath);
            msg.Attachments.Add(att);

            SmtpClient client = new SmtpClient(serverAddress, serverPort);
            client.Credentials = creds;
            client.EnableSsl = true;
            client.Send(msg);
            msg.Dispose();
        }


Try using SendAsync() instead. It has a callback when it's completed. In the callback, delete your files.

The callback is client.SendCompleted on the SMPTClient class.

If nothing else, it may give a clue as to what is going on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜