简体   繁体   中英

PDF Outlook Email attachment sometimes saved with no permissions

Looping through messages (getItem object) in an Outlook message store and saving attachments as files using the code below:

try 
{
      foreach (Outlook.Attachment attach in getItem.Attachments)
      {
           if (attach.FileName == sItemName)
           {
                string sSaveFile = Path.GetTempPath() + "Attachment" + sItemType;
                if (System.IO.File.Exists(sSaveFile)) System.IO.File.Delete(sSaveFile);
                attach.SaveAsFile(sSaveFile);
                sContent = Common.GetFileContent2(sSaveFile);
           }
      }
 }
 catch (Exception Ex)
 {
      Common.LogError("GetUpdated", Ex, "Get text from Email attachment", "Error", false);
 }
 System.Runtime.InteropServices.Marshal.ReleaseComObject(getItem.Attachments);

I find that the extracted PDF file is sometimes inaccessible for deletion when another PDF file appears. The file permissions of the extracted PDF file cannot be viewed in Explorer - the Security tab of properties says "You must have read permissions to view the properties of this object". The General properties tab can be read OK.

I am using Outlook 2007 in Windows 8.1

I'd recommend starting from reviewing the code and releasing all underlying COM objects instantly. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. This is particularly important if your add-in attempts to enumerate more than 256 Outlook items in a collection that is stored on a Microsoft Exchange Server. If you do not release these objects in a timely manner, you can reach the limit imposed by Exchange on the maximum number of items opened at any one time. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. You can read more about that in the Systematically Releasing Objects article in MSDN.

For example:

foreach (Outlook.Attachment attach in getItem.Attachments)

The Attachments property returns an instance of the Attachments class which should be released after. Also each instance of the Attachment class stays alive until the method ends and GC runs.

Finally, I'd recommend using the for loop instead. Thus, you will be able to release every object instantly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM