I am creating an Windows Form application that can generate Excel files from database data. After filling the database into the file i am opening the it and executing a macro, saving the file and then closing it (or i think i am closing it). These files are saved on my HDD but When all the files are generated i have to be able to generate a new set of files and therefor i have to delete all the old files from my HDD before generating the new set. After running the application once and i try to generate the new set of files, i get an error stating that one of the files (the last file that have been generated in the first batch) is used by another process.
here is my code:
public void RemoveRows_Macro(string fileName)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
xlWorkBook = xlApp.Workbooks.Open(fileName);
//xlApp.Visible = true;
xlApp.DisplayAlerts = true;
//Run the macro
xlApp.Run("RemoveRows", 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, 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, Type.Missing);
xlWorkBook.Save();
xlWorkBook.Close(false);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
Console.WriteLine("Error in releasing object :" + ex);
obj = null;
}
finally
{
GC.Collect();
}
}
What am i doing wrong since the application is not releasing the file ?