Creating Outlook Application Object reference not set to an instance of an object
You'll need to first try and get a reference to the running instance, and only create a new one (new Outlook.Application()
) if an existing instance can't be attached to.
This MSDN article makes it pretty clear.
Shameless rip directly from MSDN article:
Outlook.Application application = null;
// Check whether there is an Outlook process running.
if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
// If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
}
else
{
// If not, create a new instance of Outlook and log on to the default profile.
application = new Outlook.Application();
Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
nameSpace.Logon("", "", Missing.Value, Missing.Value);
nameSpace = null;
}
Niklas
Updated on June 05, 2022Comments
-
Niklas almost 2 years
Hello I am creating a new Outlook.Application (with v.14.0.0.0 Office library) and retrieving the inbox email with C#. Only when outlook is not running, I am getting the error
'Object reference not set to an instance of an object'
in a alert(Occurred by the first line). The program is runnig ahead(doesn't even go in the catch part).
try { Outlook.Application outlookApplication = new Outlook.Application(); Outlook.NameSpace mapiNameSpace = outlookApplication.GetNamespace("MAPI"); Outlook.MAPIFolder folder = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); foreach (Object obj in folder.Items) { if (obj is Outlook.MailItem) { Outlook.MailItem mailItem = (Outlook.MailItem)obj; } } } catch (Exception e) { Console.WriteLine("Unfortunately an error occurred"); Console.WriteLine(e.Message); }
Is there any solution for this annoying alert? Can I suppress it or fix the problem?
The alert is coming from a Outlook instance, I can see it because in the navigation bar a outlook instance is open (the little alert dialog).