Created
April 28, 2013 23:03
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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