Reputation: 7105
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?
Upvotes: 0
Views: 1712
Reputation: 49219
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).
Upvotes: 0