0

I have a ClickOnce application that needs to determine if an excel file exists or not, in order to decide whether to create it or write over it.

        Excel.Workbook workBook;
        if (File.Exists(fullFilePath)) {
            workBook = excelApp.Workbooks.Open(fullFilePath);
        } else {
            workBook = excelApp.Workbooks.Add(ApplicationDeployment.CurrentDeployment.DataDirectory + @"\" + TEMPLATE_NAME);
            workBook.SaveAs(path + "\\" + fileName, Excel.XlFileFormat.xlWorkbookNormal);
        }

This works fine the first time the application is installed and used, but if I restart the application it no longer sees the file if it exists, causing the SaveAs to be executed and causing an exception. The exception is System.Runtime.InteropServices.COMException (0x800A03EC).

  • I think you need to properly close and cleanup your Excel objects by calling Marshal.ReleaseComObject(excelApp) etc. Read this: http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects – Jon Jul 14 '16 at 20:56
  • 1
    What is `path`? You check if `fullFilePath` exists, if it doesn't then you create `path\fileName` instead of `fullFilePath`; maybe this is your problem. And to add slightly and clarify what Mangist said, you are for example creating a `Excel.Workbooks` object possibly without knowing it when you access `excelApp.Workbooks`. So in just the code posted you have 3 objects that need to be released, the application `excelApp`, the workbook `workBook`, and also the currently unassigned `Workbooks` object. – Quantic Jul 14 '16 at 21:01

1 Answers1

0

Well, that was stupid. I was accidentally adding a newline to the file name when the application starts up, which I didn't notice because the file name is displayed on a single line textbox... oh boy.