File locked after sending it as attachment

前端 未结 6 1432
-上瘾入骨i
-上瘾入骨i 2020-12-10 13:20

I am sending a file as an attachment:

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(filePa         


        
相关标签:
6条回答
  • 2020-12-10 13:28

    In order to prevent this file lock from happening, you could use using as this will dispose of the object automatically:

    using (Attachment data = new Attachment(filePath, MediaTypeNames.Application.Octet))
    {
        // Add time stamp information for the file.             
        ContentDisposition disposition = data.ContentDisposition;   
        disposition.CreationDate = System.IO.File.GetCreationTime(filePath);
        disposition.ModificationDate = System.IO.File.GetLastWriteTime(filePath);
        disposition.ReadDate = System.IO.File.GetLastAccessTime(filePath);
        // Add the file attachment to this e-mail message.
        message.Attachments.Add(data); 
        // Add your send code in here too
    }
    
    0 讨论(0)
  • 2020-12-10 13:29

    You need to take advantage of "using" keyword:

    using(Attachment att = new Attachment(...))
    {
       ...
    }
    

    That's because "using" ensures IDisposable.Dispose method is called at the end of code block execution.

    Whenever you use some class that's managing some resource, check if it's IDisposable and then use "using" block and you won't need to care about manually disposing calling IDisposable.Dispose.

    0 讨论(0)
  • 2020-12-10 13:31

    Attachments are IDisposable and should be disposed of correctly after they have been sent to release the lock on the file

    0 讨论(0)
  • 2020-12-10 13:32

    A shared similar problem. I had to use image.dispose() on a given image before I could do something with the file that the image was created from.

    0 讨论(0)
  • 2020-12-10 13:34

    Disposing your message will fix this for you. Try calling Dispose on your message before moving the file, like so:

    message.Dispose();
    File.Move(...)
    

    When disposing MailMessage, all locks and resources are released.

    0 讨论(0)
  • 2020-12-10 13:46

    Here's another way to dispose of the Attachments, once you've finished with them...

    //  Prepare the MailMessage "mail" to get sent out...
    await Task.Run(() => smtp.Send(mail));
    
    //  Then dispose of the Attachments.
    foreach (Attachment attach in mail.Attachments)
    {
        //  Very important, otherwise the files remain "locked", so can't be deleted
        attach.Dispose();
    }
    
    0 讨论(0)
提交回复
热议问题