Search code examples
c#castingoutlook-addinoutlook-2007email-attachments

Converting an Microsoft.Office.Interop.Outlook.Attachment to System.Net.Mail.Attachment in c#


I'm currently programming an addon to Outlook 2007 and I ran into a problem when I tried to Serialize an attachment. Although System.Net.Mail Attachments have a ContentStream that I can use to serialize the data, Microsoft.Office.Interop.Outlook Attachments does not. Unfortunately, the only type of attachment I can get directly from Outlook is the Microsoft.Office.Interop.Outlook one. I've searched around a bit and haven't been able to find anything similar.

MailItem item = getMailObj(e);    
String dataSend = serializeAttachment((System.Net.Mail.Attachment)item.Attachments[1]);

As you can see, I tried typecasting the initial attachment, but i was given an Invalid Cast Exception:

Unable to cast COM object of type 'System.__ComObject' to class type 'System.Net.Mail.Attachment'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.

I also cannot just put

System.Net.Mail.Attachment newAtt = item.Attachments[1];

As VisualStudio 2010 just tells me to typecast it. Any suggestions on how to fix this?


Solution

  • I don't think that types can be casted or converted. Just read content of Outlook attachment and write it to Mail.Attachment.