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.)");
}
try/catch/finallystatement. It is unclear “where” the last code snippet is called.Console.WriteLine("Next message will be sent in: " + MessageDelay + " seconds. (Specified in Config.)");… then the Excel app will still be visible in the task manager even though the code has released it. When the app exits, then the Excel app should get removed from the task manager.