Question

I'm running Excel from a C# .Net application and having trouble getting the process to shut down. How can I get the Excel process to shut down correctly from my C# program?

Was it helpful?

Solution

Try this:

foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
        {
            if (process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE"))
            {
                process.Kill();
                break;
            }
        }

OTHER TIPS

I'm about 99% certain that your problem is caused by dangling COM references preventing the Excel process from shutting down. Excel is particularly prone to this as it tends to transparently generate COM references without giving you the means to get at their handles and explicitly shut them down.

The PIAs compound this problem by making their own set of references to the underlying COM objects that they do not clean up unless you explicitly make them do it. Working with Excel through the PIAs is quite fiddly for precisely this reason.

Application.Quit() (IIRC this is what it's called) will shut down the process if the references are all correctly cleaned up. This means that you have to carefully manage the life cycle of anything that holds COM references to the Excel process and make sure that all COM references are cleaned up properly.

Application app = new Application();
...
EndTask((IntPtr)app.Hwnd, true, true);

[DllImport("user32.dll")]
public static extern bool EndTask(IntPtr hwnd, bool shutdown, bool force);

Depending on your needs, you might consider using SpreadsheetGear for .NET which gives you an Excel compatible component with no COM Interop (no hanging instances, better performance, don't have to worry whether Excel is installed or which version of Excel is installed).

You can see live ASP.NET samples with C# and VB source here, learn more about SpreadsheetGear's Windows Forms controls and samples here, and download a free trial here if you want to try it yourself.

Disclaimer: I own SpreadsheetGear LLC

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top