Excel Process will not terminate with Excel-Introp - c#

I have been trying to import data from an excel sheet into a DataTable. The problem is that after i finish, excel would not terminate the process. I do not want to terminate by process name using System.Diagnostics as that approach would terminate all excel instances rather than the one that was created by the application. I know that this question was posted over here before multiple times, but none of the solutions seem to work for me. I am probably missing something and can not see it.
below is my code:
private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Excel WorkBooks (*.xlsx)|*.xlsx";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string empRange = "D4";
string emptxid = "K4";
object oMissing = System.Reflection.Missing.Value;
string path = openFileDialog1.FileName;
oExcel.Application xlApp;
oExcel.Workbooks xlWorkBooks;
oExcel.Workbook xlWorkBook;
oExcel.Sheets xlSheets;
oExcel.Worksheet xlWorkSheetDATA;
oExcel.Worksheet xlWorkSheetEMP;
oExcel.Range range;
xlApp = new oExcel.Application();
xlWorkBooks = xlApp.Workbooks;
xlWorkBook = xlWorkBooks.Open(path);
xlSheets = xlWorkBook.Worksheets;
xlWorkSheetDATA = (oExcel.Worksheet)xlSheets.get_Item(DATASheetName);
xlWorkSheetEMP = (oExcel.Worksheet)xlSheets.get_Item(EMPSheetName);
xlWorkSheetEMP.Activate();
range = xlWorkSheetEMP.get_Range(empRange, empRange);
xlWorkSheetDATA.Activate();
range = xlWorkSheetDATA.get_Range(emptxid, emptxid);
xlApp.DisplayAlerts = false;
xlWorkSheetDATA.Columns.ClearFormats();
xlWorkSheetDATA.Rows.ClearFormats();
int iTotalColumns = xlWorkSheetDATA.UsedRange.Columns.Count;
int iTotalRows = xlWorkSheetDATA.UsedRange.Rows.Count;
xlApp.Visible = true;
DataTable dt = new DataTable();
addColumns(iTotalColumns, dt);
insertIntoDataTable(iTotalRows, dt, path);
//clean-up
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
range = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheetEMP);
xlWorkSheetEMP = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheetDATA);
xlWorkSheetDATA = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets);
xlSheets = null;
xlWorkBook.Close(false);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
xlWorkBook = null;
xlWorkBooks.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBooks);
xlWorkBooks = null;
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
}

Write a method to release the objects such as this example
private void ReleaseOfficeObject(object o)
{
Marshal.ReleaseComObject(o);
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(o);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
then to call it
ReleaseOfficeObject(range);
ReleaseOfficeObject(xlWorkSheetDATA);
ReleaseOfficeObject(xlSheets);
xlWorkBook.Close(false);
ReleaseOfficeObject(xlWorkBook);
xlWorkBook = null;
xlWorkBooks.Close();
ReleaseOfficeObject(xlWorkBooks);
xlWorkBooks = null;
xlApp.Quit();
ReleaseOfficeObject(xlApp);

You never need to call Marshal.ReleaseComObject in this context. The runtime is perfectly able to keep track of COM objects and release them when they are no longer referenced. Calling Marshal.ReleaseComObject is a confusing anti-pattern that sadly even some Microsoft documentation mistakenly suggests. You also don't have to set local variables to null - the references in local variables will be out of scope when the method completes.
You do have to be careful with this kind of code in debug builds. References in a method are artificially kept alive until the end of the method so that they will still be accessible in the debugger. This means your local xlApp variable might not be cleaned up by calling the GC inside that method.
You should run the garbage collection twice, reference cycles could be broken in the first collection, but you need a second collection to be sure all cleanup is done for those references.
To avoid this issue, you might follow a pattern like this:
private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Excel WorkBooks (*.xlsx)|*.xlsx";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string path = openFileDialog1.FileName;
// Call another method that wraps all the Excel COM stuff
// That prevents debug builds from confusing the lifetime of COM references
DoExcelStuff(path);
// When back here, all the Excel references should be out of scope
// Run the GC (twice) to clean up all COM references
// (This can be pulled out into a helper method somewhere)
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
private void DoExcelStuff(string path)
{
// All your Excel COM interop goes here
string empRange = "D4";
string emptxid = "K4";
object oMissing = System.Reflection.Missing.Value;
// ... variable declarations
xlApp = new oExcel.Application();
// More xlApp, workbooks etc...
// Done - tell Excel to close
xlApp.Quit();
// No need for Marshal.ReleaseComObject(...)
// or setting variables to null here!
}

Related

Excel does not Quit C#

I am writing this particular code in C# to write to an excel file.
public partial class WriteExcelForm : Form
{
public WriteExcelForm()
{
InitializeComponent();
}
private void writeExcelButton_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not installed!!!");
return;
}
Excel.Workbooks xlWorkBooks = xlApp.Workbooks;
Excel.Workbook xlWorkBook = xlWorkBooks.Add(Type.Missing);
Excel.Worksheet xlWorkSheet = xlWorkBook.ActiveSheet;
xlWorkSheet.Name = "sample";
Excel.Range range1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
range1.Value = "dhiraj";
Excel.Range range2 = xlWorkSheet.Range["A2"];
range2.Value = "dhiraj";
xlWorkBook.SaveAs("C:\\output.xlsx");
//Properly closing the excel app
GC.Collect();
GC.WaitForPendingFinalizers();
xlWorkBook.Close(false, Type.Missing, Type.Missing);
xlApp.Quit();
Marshal.FinalReleaseComObject(range1);
Marshal.FinalReleaseComObject(range2);
Marshal.FinalReleaseComObject(xlWorkSheet);
Marshal.FinalReleaseComObject(xlWorkBook);
Marshal.FinalReleaseComObject(xlWorkBooks);
Marshal.FinalReleaseComObject(xlApp);
}
}
If I run this code, the excel.exe does not quit, but keeps on hanging around in the background.
However, if I comment out this particular line
Excel.Range range1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
range1.Value = "dhiraj";
the excel.exe quits elegantly.
What am I missing here?
EDIT:
I have solved my issue. Posting my findings as answer.
P.S: Do not know why I was down voted, I did research a lot before posting this question.
So, I continued my research after asking the question, and I found this particular link
How do I properly clean up Excel interop objects?
Now in this particular link, three answers which when put together helped me out.
First answer is this particular one https://stackoverflow.com/a/158752/2241802
It says to avoid using "Never use two dots with COM objects".
Second answer is this one https://stackoverflow.com/a/159419/2241802
This answer refers to how to use excel object practically and it is very important to follow this, since I will not be the only developer working on my piece of code.
The third answer https://stackoverflow.com/a/1893653/2241802
talks about the how Garbage Collector behavior differs in Release mode and Debug mode.
So that was my problem, when i ran the code pasted in the question in Release mode, it worked fine and the excel.exe quit gracefully.
However, to make it work in the Debug mode I took the suggestion of the Thrid Answer link above and created a function which implemented the excel writing stuff.
Find below code
protected void Button3_Click(object sender, EventArgs e)
{
int randomvalue = new Random().Next(10);
try
{
filename = Server.MapPath("~/Reports/Tro_Reports" + randomvalue + ".xlsx");
using (var getReportCollection = new DataSet1())
{
using (var tableCollection = getReportCollection.Tables["SheetNames"])
{
var excelApplication = new Microsoft.Office.Interop.Excel.Application();
try
{
var wb = excelApplication.Workbooks.Add();
var collection = new Microsoft.Office.Interop.Excel.Worksheet[20];
for (var i = 0; i < tableCollection.Columns.Count; i++)
{
collection[i] = wb.Worksheets.Add();
collection[i].Name = tableCollection.Columns[i].ToString();
}
var thisWorksheet = collection[2];
var thisRange = thisWorksheet.Range["A1"];
thisRange.Value = "Event Summary Report";
wb.SaveAs(filename);
wb.Close();
}
finally
{
Marshal.ReleaseComObject(excelApplication);
}
}
}
}
catch (ExternalException ex)
{
}
}
The above code snippet will work fine to close your excel sheet.

Excel process not closing [duplicate]

This question already has answers here:
How do I properly clean up Excel interop objects?
(43 answers)
Closed 9 years ago.
I've got this C# program that never closes the Excel process. Basically it finds the number of instances a string appears in a range in Excel. I've tried all kinds of things, but it's not working. There is a Form that is calling this method, but that shouldn't change why the process isn't closing. I've looks at suggestions by Hans Passant, but none are working.
EDIT: I tried the things mentioned and it still won't close. Here's my updated code.
EDIT: Tried the whole Process.Kill() and it works, but it seems like a bit of a hack for something that should just work.
public class CompareHelper
{
// Define Variables
Excel.Application excelApp = null;
Excel.Workbooks wkbks = null;
Excel.Workbook wkbk = null;
Excel.Worksheet wksht = null;
Dictionary<String, int> map = new Dictionary<String, int>();
// Compare columns
public void GetCounts(string startrow, string endrow, string columnsin, System.Windows.Forms.TextBox results, string excelFile)
{
results.Text = "";
try
{
// Create an instance of Microsoft Excel and make it invisible
excelApp = new Excel.Application();
excelApp.Visible = false;
// open a Workbook and get the active Worksheet
wkbks = excelApp.Workbooks;
wkbk = wkbks.Open(excelFile, Type.Missing, true);
wksht = wkbk.ActiveSheet;
...
}
catch
{
throw;
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (wksht != null)
{
//wksht.Delete();
Marshal.FinalReleaseComObject(wksht);
wksht = null;
}
if (wkbks != null)
{
//wkbks.Close();
Marshal.FinalReleaseComObject(wkbks);
wkbks = null;
}
if (wkbk != null)
{
excelApp.DisplayAlerts = false;
wkbk.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(wkbk);
wkbk = null;
}
if (excelApp != null)
{
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
excelApp = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
/*
Process[] processes = Process.GetProcessesByName("EXCEL");
foreach (Process p in processes)
{
p.Kill();
}
*/
}
}
}
Here is an interesting knowledge base on the subject of office apps staying open after a .NET app disconnects from them.
Office application does not quit after automation from Visual Studio .NET client
The code examples are all in the link (vb.net sorry). Basically it shows you how to correctly setup and tear down the office app so that it closes when you're finished with it.
System.Runtime.InteropServices.Marshal.FinalReleaseComObject is where the magic happens.
EDIT: You need to call the FinalReleaseComObject for each excel object that you've created.
if (excelWorkSheet1 != null)
{
Marshal.FinalReleaseComObject(excelWorkSheet1);
excelWorkSheet1 = null;
}
if (excelWorkbook != null)
{
Marshal.FinalReleaseComObject(excelWorkbook);
excelWorkbook = null;
}
if (excelApp != null)
{
Marshal.FinalReleaseComObject(excelApp);
excelApp = null;
}
I finally got it to close. You need to add a variable for the Workbooks collection, and then use the FinalReleaseComObject as stated in the other answers. I guess every possible Excel COM object that you use must be disposed this way.
try
{
// Create an instance of Microsoft Excel and make it invisible
excelApp = new Excel.Application();
excelApp.DisplayAlerts = false;
excelApp.Visible = false;
// open a Workbook and get the active Worksheet
excelWorkbooks = excelApp.Workbooks;
excelWorkbook = excelWorkbooks.Open(excelFile, Type.Missing, true);
excelWorkSheet1 = excelWorkbook.ActiveSheet;
}
catch
{
throw;
}
finally
{
NAR( excelWorkSheet1 );
excelWorkbook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
NAR(excelWorkbook);
NAR(excelWorkbooks);
excelApp.Quit();
NAR(excelApp);
}
}
private void NAR(object o)
{
try
{
System.Runtime.InteropServices.Marshal.FinalReleaseComObject( o );
}
catch { }
finally
{
o = null;
}
}
DotNet only release the COM object after all the handles have been released. What I do is comment everything out, and then add back a portion. See if it release Excel. If it did not follow the following rules. When it release, add more code until it does not release again.
1) When you create your Excel variables, set all the values to null (this avoid not initiated errors)
2) Do not reuse variables without releasing it first Marshal.FinalReleaseComObject
3) Do not double dot (a.b = z). dotNet create a temporary variable, which will not get released.
c = a.b;
c = z;
Marshal.FinalReleaseComObject(c);
4) Release ALL excel variables. The quicker the better.
5) Set it back to NULL.
Set culture to "en-US". There is a bug that crash Excel with some cultures. This ensure it won't.
Here is an idea of how your code should be structured:
thisThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
InteropExcel.Application excelApp = null;
InteropExcel.Workbooks wkbks = null;
InteropExcel.Workbook wkbk = null;
try
{
excelApp = new InteropExcel.Application();
wkbks = excelApp.Workbooks;
wkbk = wkbks.Open(fileName);
...
}
catch (Exception ex)
{
}
if (wkbk != null)
{
excelApp.DisplayAlerts = false;
wkbk.Close(false);
Marshal.FinalReleaseComObject(wkbk);
wkbk = null;
}
if (wkbks != null)
{
wkbks.Close();
Marshal.FinalReleaseComObject(wkbks);
wkbks = null;
}
if (excelApp != null)
{
// Close Excel.
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
excelApp = null;
}
// Change culture back from en-us to the original culture.
thisThread.CurrentCulture = originalCulture;
}

"DisconnectedContext was detected" error when releasing Excel object in C#

I am trying to release Excel objects after using them. Here is my code:
Excel._Application app = new Excel.Application();
Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet.Cells[1, 1] = "test string";
workbook.SaveAs("C:\testfile.xlsx");
object misValue = System.Reflection.Missing.Value;
workbook.Close(true, misValue, misValue);
app.Quit();
releaseObject(worksheet);
releaseObject(workbook);
releaseObject(app);
My releaseObject method:
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
At the first time the debugger goes into releaseObject, it gives an error in first "GC.WaitForPendingFinalizers();" line:
Context 0xdf76a0' is disconnected. Releasing the interfaces from the
current context (context 0xdf7450). This may cause corruption or data
loss. To avoid this problem, please ensure that all
contexts/apartments stay alive until the application is completely
done with the RuntimeCallableWrappers that represent COM components
that live inside them.
How can I figure it out?

Safely disposing Excel interop objects in C#?

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 would like to know how can i make sure that the objects are released even when there is an error?
here's my code:
private void button1_Click(object sender, EventArgs e)
{
string myBigFile="";
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
myBigFile=openFileDialog1.FileName;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(myBigFile, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
/*
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
MessageBox.Show(str);
}
}
*/
xlWorkSheet..EntireRow.Delete(Excel.XLDirection.xlUp)
xlWorkBook.SaveAs(xlWorkBook.Path + #"\XMLCopy.xls", Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
how can i make sure that even if i get an error after the workbook opened, that i make sure to dispose of the objects:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
In other words no matter what i need the following lines to run
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
please note that i have tried this as well, resulting in the same issue
xlWorkBook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
xlWorkSheet = null;
xlWorkBook = null;
xlApp = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
and i did this as well:
GC.Collect() ;
GC.WaitForPendingFinalizers();
GC.Collect() ;
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(xlWorkSheet);
xlWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlWorkBook);
xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);
at this point i do not think it's possible to close excel from visual studio 2008. it must be a bug or something, but i've tried the top 20 websites on this and getting the same result: excel is opening two instances for some reason and when i do the garbage collection etc.. (or not) it closes just ONE instance.
when i try to open the file, it says there's an error or it's corrupt.
when i go to task manager and kill the excel process, the file will open without problems.]
is there a way to close excel with visual studio 2008? if so, can you please provide me with guidance or a solution to this
First I will present a modified releaseObject, and then I will provide a pattern to use it.
using Marshal = System.Runtime.InteropServices.Marshal;
private void releaseObject(ref object obj) // note ref!
{
// Do not catch an exception from this.
// You may want to remove these guards depending on
// what you think the semantics should be.
if (obj != null && Marshal.IsComObject(obj)) {
Marshal.ReleaseComObject(obj);
}
// Since passed "by ref" this assingment will be useful
// (It was not useful in the original, and neither was the
// GC.Collect.)
obj = null;
}
Now, a pattern to use:
private void button1_Click(object sender, EventArgs e)
{
// Declare. Assign a value to avoid a compiler error.
Excel.Application xlApp = null;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;
try {
// Initialize
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(myBigFile, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 1, 0);
// If the cast fails this like could "leak" a COM RCW
// Since this "should never happen" I wouldn't worry about it.
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
...
} finally {
// Release all COM RCWs.
// The "releaseObject" will just "do nothing" if null is passed,
// so no need to check to find out which need to be released.
// The "finally" is run in all cases, even if there was an exception
// in the "try".
// Note: passing "by ref" so afterwords "xlWorkSheet" will
// evaluate to null. See "releaseObject".
releaseObject(ref xlWorkSheet);
releaseObject(ref xlWorkBook);
// The Quit is done in the finally because we always
// want to quit. It is no different than releasing RCWs.
if (xlApp != null) {
xlApp.Quit();
}
releaseObject(ref xlApp);
}
}
This simple approach can be extended/nested over most situations. I use a custom wrapper class that implements IDisposable to make this task easier.
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.

Excel process remains open after interop; traditional method not working

I'm running into an issue with some code I'm debugging. Excel interop is used to extract some values from a workbook; however, Excel remains open after the program has exited. I've tried the traditional solution, but it still keeps a reference to Excel open on all machines where the code is run
private void TestExcel()
{
Excel.Application excel = new Excel.Application();
Excel.Workbooks books = excel.Workbooks;
Excel.Workbook book = books.Open("C:\\test.xlsm");
book.Close();
books.Close();
excel.Quit();
Marshal.ReleaseComObject(book);
Marshal.ReleaseComObject(books);
Marshal.ReleaseComObject(excel);
}
Even this simple piece of code keeps the process running with multiple files (xlsm, xlsx, xls). Right now we have a workaround in place to kill the Excel processes we've opened, but I'd much rather get this working for my own sanity.
I should add that I have it narrowed down to the Workbook variable. If I remove the call to books.Open() and all references to book then it closes successfully.
This has worked successfully for me:
xlApp.Quit();
//release all memory - stop EXCEL.exe from hanging around.
if (xlWorkBook != null) { Marshal.ReleaseComObject(xlWorkBook); } //release each workbook like this
if (xlWorkSheet != null) { Marshal.ReleaseComObject(xlWorkSheet); } //release each worksheet like this
if (xlApp != null) { Marshal.ReleaseComObject(xlApp); } //release the Excel application
xlWorkBook = null; //set each memory reference to null.
xlWorkSheet = null;
xlApp = null;
GC.Collect();
This code works for me.
//Declare separate object variables
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks xlWorkbooks = xlApp.Workbooks;
Excel.Workbook xlWorkbook = xlWorkbooks.Add(Missing.Value);
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);
//Create worksheet
xlWorkbook.Close(false, Missing.Value, Missing.Value);
xlWorkbooks.Close();
xlApp.Quit();
Marshal.FinalReleaseComObject(xlWorksheet);
Marshal.FinalReleaseComObject(xlWorkbook);
Marshal.FinalReleaseComObject(xlWorkbooks);
Marshal.FinalReleaseComObject(xlApp);
xlWorksheet = null;
xlWorkbook = null;
xlWorkbooks = null;
xlApp = null;
GC.Collect();
This article from Microsoft has some good information regarding this issue.
I am a total COM amateur, used it for a minor thing in one project quite a long time ago, but here's a snippet I used there. I probably found it somewhere online, don't remember. In any case, I paste it its full glory ;)
public static class ComBlackBox
{
public static void ReleaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (ArgumentException ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.Message);
}
finally
{
GC.Collect();
}
}
}
I'm unable to try it out now, but it probably worked (I honestly don't remember any details). Maybe it will help you out. Feel free to point out any obvious problems with this code, I really am far from being COM-literate ;)
This is how I got around this problem:
// Store the Excel processes before opening.
Process[] processesBefore = Process.GetProcessesByName("excel");
// Open the file in Excel.
Application excelApplication = new Application();
Workbook excelWorkbook = excelApplication.Workbooks.Open(Filename);
// Get Excel processes after opening the file.
Process[] processesAfter = Process.GetProcessesByName("excel");
// Now find the process id that was created, and store it.
int processID = 0;
foreach (Process process in processesAfter)
{
if (!processesBefore.Select(p => p.Id).Contains(process.Id))
{
processID = process.Id;
}
}
// Do the Excel stuff
// Now close the file with the COM object.
excelWorkbook.Close();
excelApplication.Workbooks.Close();
excelApplication.Quit();
// And now kill the process.
if (processID != 0)
{
Process process = Process.GetProcessById(processID);
process.Kill();
}

Categories