Skip to content

Instantly share code, notes, and snippets.

@Oblongmana
Created April 28, 2013 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oblongmana/5478776 to your computer and use it in GitHub Desktop.
Save Oblongmana/5478776 to your computer and use it in GitHub Desktop.
This adds an #Extension method to #Object (necessary as there are loads of different types of COM object, but with no more specific superclass other than Object) which will properly release a #COM object. This is oriented towards #Excel so it includes code to close workbooks, and properly quit Excel Applications - could easily be extended with a…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace AnalysisSuite.Extensions
{
public static class ObjectExtensions
{
public static void CloseReleaseAndNullComObject(this object o)
{
//http://support.microsoft.com/kb/317109
try
{
if ((o as Excel.Workbook) !=null) ((Excel.Workbook)o).Close();
if ((o as Excel.Workbooks) != null) ((Excel.Workbooks)o).Close();
if ((o as Excel._Application) != null)
{
((Excel._Application)o).Visible = true;
((Excel._Application)o).ScreenUpdating = true;
((Excel._Application)o).DisplayAlerts = true;
((Excel._Application)o).Quit();
}
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(o);
}
catch { }
finally
{
o = null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment