tags:

views:

29

answers:

1

I use said invocation to release some Excel objects after I'm done. Is it necessary to set references to null afterwards (like in the following code) ?

var dateCol = sheet1.get_Range("C4", "C" + rowOffset);
dateCol.NumberFormat = "Text";
Marshal.ReleaseComObject(dateCol);
dateCol = null;
A: 

This is what I always use and it works very well

using Excel = Microsoft.Office.Interop.Excel; 

    Excel.ApplicationClass _Excel; 
    Excel.Workbook WB; 
    Excel.Worksheet WS; 

try 
    { 

    _Excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
    WB = _Excel.Workbooks.Open("FILENAME", 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing); 

        //do something 

    } 
    catch (Exception ex) 
    { 
        WB.Close(false, Type.Missing, Type.Missing); 

        throw; 
    } 
    finally 
    { 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 

        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB); 

        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel); 


    } 

Do a

System.Runtime.InteropServices.Marshal.FinalReleaseComObject

On all referenced Excel objects

Gratzy
Thanks! I 'll be sure to use it. It seems that sometimes Excel will hang despite my code above... so it looks like this is the way to go.
Ioannis Karadimas