Sometimes the libraries you need can not be compiled into the code you are writing. But this doesn’t mean that you can’t still use them, using reflection you can load any library dynamically into your code and execute any method within it.

The below example demonstrates how to dynamically load the Microsoft Interop Library for Outlook from a directory and subsequently invoke a new Email with an attachment. I’ve commented the code above each invocation with the equivalent code that would be used if this library had been loaded at compile time.

Assembly interopAssembly = Assembly.LoadFile(System.Environment.CurrentDirectory + @"\Microsoft.Office.Interop.Outlook.dll");

 //Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
 object outlookApplication = interopAssembly.CreateInstance("Microsoft.Office.Interop.Outlook.ApplicationClass");
 Type outlookApplicationType = interopAssembly.GetType("Microsoft.Office.Interop.Outlook.ApplicationClass");

 //Microsoft.Office.Interop.Outlook._MailItem oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
 dynamic mailItem = outlookApplicationType.InvokeMember("CreateItem", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, outlookApplication, new object[] { 0 });

 mailItem.To = "";
 mailItem.Subject = "";
 mailItem.Body = "";

 //oMailItem.Attachments.Add(@"C:\Logs\ContractImpl_2.txt", Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
 object attachments = mailItem.Attachments;
 Type attachmentType = attachments.GetType();
 attachmentType.InvokeMember("Add", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, attachments, new object[] { @"C:\Logs\ContractImpl_2.txt", 1, Type.Missing, Type.Missing });

 Type mailItemType = mailItem.GetType();
 mailItemType.InvokeMember("Display", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, mailItem, new object[] { true });
Be Sociable, Share!

Tags: , , ,