0

I am creating a Forms application using C# and the Interop.Excel library to read and write data to an Excel spreadsheet. There is a problem where Excel will spawn processes, but they won't close even after I call the function that should close it. Here is an example of my code handling closing of the Excel application:

var excel = new Microsoft.Office.Interop.Excel.Application();
var workbooks = excel.Workbooks;
Workbook workbook = null;
Worksheet worksheet = null;
[insert code here where all the Excel spreadsheets are properly imported and exported ect]
workbook.Save();
workbook.Close(0);
workbooks.Close();
excel.Quit();

I remember that the majority of answers I found online to my problem recommended that I use Marshal.ReleaseComObject(excel); or something to that effect. However, I also found that Microsoft considers Marshal.ReleaseComObject dangerous and recommends not to use it.

Is there a safe way to use Marshal.ReleaseComObject? Or is there another solution to my problem?

  • 2
    The best solution, if you are only working with xlsx files is not use the interop at all and instead use the newer sdk provided by microsoft. https://www.nuget.org/packages/DocumentFormat.OpenXml/ – Scott Chamberlain Oct 20 '18 at 06:05
  • All you have to do is force the garbage collector to run, GC.Collect(). But almost everybody puts it in the wrong place, after the Quit() call. [Doesn't work when you debug the code](https://stackoverflow.com/a/17131389/17034). Put it in the caller of this method instead. – Hans Passant Oct 20 '18 at 08:38
  • @HansPassant So lets assume that the stuff I put in a function called foo(). Should I run the GC.Collect() command immediately after foo() is called? – user10531867 Oct 21 '18 at 07:18

0 Answers0