'Not all instances of Excel application closing after running code
This is the code, I have seen in several other places to close instances of the objects with Marshal.FinalReleaseComObject(...)
This method is called everytime a successful message is sent.
public static Excel.Workbook MyBook = null;
public static Excel.Application MyApp = null;
public static Excel.Worksheet MySheet = null;
private static void SuccessLog(string communicationMethod, string portNumber, int messageDelay)
{
Console.WriteLine(Environment.NewLine);
DateTime startTime = DateTime.Now;
string trimDate = Convert.ToString(startTime.ToShortDateString()).Replace('/', '_');
string folder = @"C:\Temp\";
string fileName = Convert.ToString(trimDate);
string message = "Message Sent At: " + Convert.ToString(startTime) + ", via " + communicationMethod + ", at port # " + portNumber + "." + Environment.NewLine;
string fullPath = folder + fileName;
MyApp = new Excel.Application();
MyApp.Visible = false;
var workbooks = MyApp.Workbooks;
if (!File.Exists(fullPath + ".xlsx"))
{
MyBook = workbooks.Add();
MySheet = MyBook.Sheets[1]; // Explicit cast is not required here
int lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
MySheet.Cells[lastRow, 1] = "asdfsa";
MySheet.Cells[lastRow, 2] = "asdfsa";
MySheet.Cells[lastRow, 3] = "asdfsa";
MySheet.Cells[lastRow, 4] = "asdfsa";
MyBook.SaveAs(fullPath);
MyBook.Close(0);
}
else
{
MyBook = workbooks.Open(fullPath + ".xlsx");
MySheet = MyBook.Sheets[1]; // Explicit cast is not required here
int lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
lastRow ++;
MySheet.Cells[lastRow, 1] = "exists?";
MySheet.Cells[lastRow, 2] = "exists?";
MySheet.Cells[lastRow, 3] = "exists?";
MySheet.Cells[lastRow, 4] = "exists?";
MyBook.Save();
MyBook.Close(0);
}
Here is where I am trying to close all of the Objects that I am creating. I think I may possibly be missing some of the objects.
MyApp.Quit();
Marshal.FinalReleaseComObject(MySheet);
Marshal.FinalReleaseComObject(MyBook);
Marshal.FinalReleaseComObject(MyApp);
Marshal.FinalReleaseComObject(workbooks);
Console.WriteLine("Log has been successfully updated or added at: " + fullPath);
Console.WriteLine("Next message will be sent in: " + MessageDelay + " seconds. (Specified in Config.)");
}
Solution 1:[1]
Various versions of excel have, for about 2 weeks now, not closed properly, and keep a lock to accdb files even though (using ADO) the connection is closed and the object is set to nothing. Since Office versions vary, I have to assume that Windows (10) has managed to break yet another thing. Until about 2 weeks ago none of this was an issue. Yay Microsoft!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Arkadi Romijn |