Excel COM Exception when invoking SaveAs method

936 views Asked by At

In my C# code, I firstly open an Excel file:

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(modelFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

Then I edit it.

Finally I save it in a different path called fileName:

xlWorkBook.SaveAs(fileName);

The problem is that if fileName corresponds to an opened Excel file, the instruction above fires the COM Exception:

System.Runtime.InteropServices.COMException occurred
ErrorCode=-2146827284
HResult=-2146827284
HelpLink=xlmain11.chm
Message=Unable to access 'MyFile.xlsx'.
Source=Microsoft Excel

Please note that I don't have the same problem with the xlWorkBook.Save() method, but I need to save the edited file in a different path and not to override it.

1

There are 1 answers

0
Ricardo Santi On

You cannot save to an open file. You would have to modify fileName so it points to another path.