I'm aware of the many similar questions, raised here and I've gone through most of them without finding a solution to satisfy my curiosity (I think my case is a bit more specific).
I'm trying to populate a collection from the names of the Named Ranges of an Excel workbook within my WPF application. The outcome is an Excel process running even after my application has closed. I've localized the problem to the following piece of code. Without it, all works fine:
foreach (Excel.Name name in names)
{
namedRanges.Add(name.Name);
}
So, obviously something here doesn't get released. I haven't found a way to close/dispose/quit the "Excel.Name" as with the other Excel objects. Please suggest how to do that. The workaround I'm using is killing the specific process, but I'd rather understand the problem behind this and try to come up with a more relevant solution. Here's the full code extract:
Excel.Application excel = new Excel.Application();
excel.Visible = false;
Excel.Workbooks wbooks = excel.Workbooks;
Excel.Workbook wbook = wbooks.Open(Proc.ExpenseFullPath);
ObservableCollection<string> namedRanges = new ObservableCollection<string>();
Excel.Names names = wbook.Names;
foreach (Excel.Name name in names)
{
namedRanges.Add(name.Name);
}
wbook.Close();
wbooks.Close();
excel.Quit();
Edit: I found out how to make it work. I replaced the problematic "foreach" with:
for (int i = 1; i <= names.Count; i++)
{
namedRanges.Add(names.Item(i).Name);
Marshal.FinalReleaseComObject(names.Item(i));
}