0

i want to restart Outlook everytime i open the console app , i deploy this app on pc server because no one will handle this when holiday.

Why i want to restart outlook ? because outlook in server pc receive many emails , we have apps to take the attachment and download it everyday. But the problem is sometimes the email is stuck , and we must restart outlook to gain the email that stuck.

I already try some code, and for process.start -> it works that can open outlook, but i cant close the duplicate outlook (the old one)

namespace CloseOpenOutlook
{
    class Program
    {
        static void Main(string[] args)
        {


            Process process = Process.GetCurrentProcess();
            var dupl = Process.GetProcessesByName(process.ProcessName);


            foreach (var p in dupl)
            {
                if (p.ProcessName == "OUTLOOK")
                {
                    p.Kill();

                }
            }

            Process myProcess = Process.Start("OUTLOOK");
        }
    }
}

Expected result = it will close the old outlook and open the new one

Actual result = it open the new one and not close the old one so it will be 2 Outlooks

I dont know where it goes wrong, already try from many source but still not working

codeislife
  • 15
  • 8

1 Answers1

0

There is two main ways to close Outlook using C#.

1) Kill the process, do it using the ProcessID otherwise you will close all instances of Outlook:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowThreadProcessId(HandleRef handle, out int processId);

private void OpenOutlookAndKillProcess()
{
   int pid = -1;
   //Get PID
   outlookApp = new Outlook.Application();
   HandleRef hwnd = new HandleRef(outlookApp, (IntPtr)outlookApp.Hwnd);
   GetWindowThreadProcessId(hwnd, out pid);
   .....
   //Finally
   KillProcess(pid,"OUTLOOK");
}

private void KillProcess(int pid, string processName)
{
    System.Diagnostics.Process[] AllProcesses = System.Diagnostics.Process.GetProcessesByName(processName);
    foreach (System.Diagnostics.Process process in AllProcesses)
    {
       if (process.Id == pid) process.Kill();
    }
    AllProcesses = null;
}

2) The better method is to use AutoReleaseComObject or the original VSTO-Contrib, you can see one of my answers here on how to use it: Closing Excel Workbook - System.Runtime.InteropServices.COMException : Exception from HRESULT: 0x800A03EC

What you're encountering is explained here (it relates to Outlook the way same as Excel, Word, Powerpoint): How do I properly clean up Excel interop objects?

You may find its easier to just 1) kill the process but better programmers will use 2).

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321