0

I'm using Microsoft.Office.Interop.MailItem to strip attachements from email, save them to disk, print them out and then delete them from disk. I'm having problems deleting JPG attachements, the file seems to have a lock,

Here is my code for saving each attachement,

foreach (Attachment attachment in outLookMessage.Attachments)
{
    var fileNameOnDisk = FileNameOnDisk(printFileFolder, attachment.FileName);

    attachment.SaveAsFile(fileNameOnDisk);
}

I'm not sure why there is a lock on the JPG file. Is there any way I can release this log so that I can delete the file?

Andre Lombaard
  • 6,985
  • 13
  • 55
  • 96
  • What is `FileNameOnDisk`? Is it a method you've written to save out the file to a given folder? I can 't find it at a glance in the API and if so it is likely in this method that the lock is being created (eg because when saving a handle was left open to it). – Chris Mar 26 '13 at 12:44
  • What is your code to print the attachments? You could be leaving an open handle there also. – Steve Czetty Mar 26 '13 at 12:54

2 Answers2

3

I would try using attachment.Dispose() before deleting them.

Felix
  • 1,006
  • 8
  • 22
  • Attachment is an interface and does not necessarily implement IDisposable (although classes that implement it may). – plinth Mar 26 '13 at 12:39
0

The most likely cause is that the file already exists there (and is being held) or that you don't have permission to perform the action. The first is almost assuredly the case

If the file exists, why are you writing over it? This is probably not what you want to do. Better to check if the file exists and if it is locked before you write and change the name if needed. The second answer in this question has some code for finding out if a file is locked (more specifically than just IOException).

And with regards to Chris comment to the question (great idea, Chris), if the file exists, is locked and is 0 length, chances are it's your own fault in FileNameOnDisk. Close what you open if you're returning a path (best) or open it with shared read/write and return the filestream and close it when you're done (not the best).

Community
  • 1
  • 1
plinth
  • 48,267
  • 11
  • 78
  • 120