Friday, September 16, 2011

Managing Excel exe Instances in using Excel Interop in C#

If you are familier with Excel Interop in C# you may encountered problem of terminiating the excel instances . If the application extensively use backend excel interoperablity , a lot of excel instances will be created and even if you close and dispose the object from your code it sometimes still there. Here is a piece of code that will ensure the killing of excel process.
Caution : If you did'nt terminate excel instances properly the server may slow down by accumulating the excel instances


oExcel.Quit();             

            

                try

                {

     

                    IntPtr pointer = new IntPtr(oExcel.Hwnd); // this will make sure that we are going to kill the same instance

                    oExcel.Visible = true;

                    foreach (System.Diagnostics.Process proc in System.Diagnostics.Process.GetProcessesByName("Excel"))

                    {

                        if (proc.MainWindowHandle == pointer)

                            proc.Kill();

                    }

 

                }

                catch (Exception)

                {

                  

                }


oExcel is the object of your Excel App