Safely disposing Excel interop objects in C#?

后端 未结 2 861
Happy的楠姐
Happy的楠姐 2020-12-06 01:19

i am working on a winforms c# visual studio 2008 application. the app talks to excel files and i am using Microsoft.Office.Interop.Excel; to do this.

i

2条回答
  •  伪装坚强ぢ
    2020-12-06 02:00

    Verify that there are two problems you're seeing in your code:

    • That when the program closes Excel remains as a running process
    • That when you open the Excel file your program creates you see an error in Excel saying the file is corrupted or some such

    I copied the button1 click handler and pst's releaseObject method in your edited question into a clean VS2008, C#3.5 Winform application and made a couple minor changes to eliminate both the problems I listed above.

    To fix Excel not unloading from memory, call releaseObject on the range object you created. Do this before your call to releaseObject(xlWorkSheet); Remembering all these references is what makes COM Interop programming so much fun.

    To fix the corrupt Excel file problem update your WorkBook.SaveAs method call to replace the second parameter (Excel.XlFileFormat.xlXMLSpreadsheet) with Type.Missing. The SaveAs method will handle this correctly by default.

    I'm sure the code you posted in your question is simplified to help debug the problems you're having. You should use the try..finally block pst demonstrates.

提交回复
热议问题