So I have the following code, which extracts all attachments from a Contact item (residing in a shared folder):
Outlook._Application objOutlook; //declare Outlook application
objOutlook = new Outlook.Application(); //create it
Outlook._NameSpace objNS = objOutlook.Session; //create new session
Outlook.MAPIFolder oAllPublicFolders; //what it says on the tin
Outlook.MAPIFolder oPublicFolders; // as above
Outlook.MAPIFolder objContacts; //as above
Outlook.Items itmsFiltered; //the filtered items list
oPublicFolders = objNS.Folders["Public Folders"];
oAllPublicFolders = oPublicFolders.Folders["All Public Folders"];
objContacts = oAllPublicFolders.Folders["Global Contacts"];
itmsFiltered = objContacts.Items.Restrict(strFilter);//restrict the search to our filter terms
for (int i = 1; i <= itmsFiltered.Count; i++) //loop through filtered items
{
var item = itmsFiltered[i];
Contact ctctNew = new Contact(); //create new contact
foreach (Outlook.Attachment oa in item.Attachments)
{ ctctNew.ImportedAttachments.Add(oa); }
lstContacts.Add(ctctNew); // add to the list that will be displayed in the OLV
}
return lstContacts;
This seems to work fine.
I then try and save these to a file thus:
if (!System.IO.Directory.Exists(strPath))
{ System.IO.Directory.CreateDirectory(strPath); }
foreach (Outlook.Attachment o in ctLoaded.ImportedAttachments)
{
string strFilePath = strPath + @"\" + o.FileName;
if (!File.Exists(strFilePath))
{
o.SaveAsFile(strPath + @"\" + o.FileName); //exception here
}
}
This last bit works fine for filetypes that are NOT .msg - i.e. it works fine for .pdf files etc; if it's an .msg file then I get the following exception:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in Event Management System.exe
Additional information: Cannot save the attachment. Could not complete the operation. One or more parameter values are not valid.
Can anyone shed any light?
Thanks
UPDATE: I've discovered that it's only some of the .msg files that fail to save; some of them work fine. It seems that files attached by certain users seem to work, and files by other users don't; I'm guessing it might be to do with how they attach them?
Also it appears that the code DOES save the file (despite throwing the exception), but it appears to be corrupted - a 3Kb .msg file appears in the relevant folder. Outlook won't open it, I just get a "Unable to read the item." messagebox from Outlook if I try to open the file.