C# – Exception When Opening Excel File in C# Using Interop

ccsvexcelinterop

I have a program running on a server which downloads an .xls file from a website every day, opens it then converts it to a .csv to be able to parse it correctly and add to a database.

When I run it on my local PC everything works fine and it works most of the time on the server as well, but maybe once or twice a week I get this exception:

Exception occurred: System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC
at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)

Here's a code snippet:

 Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Open(_dir + _fileNameTrim + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wbWorkbook.SaveAs(_dir + _fileNameTrim + ".csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wbWorkbook.Close(false, "", true);

I've read many things online, a lot of solutions mention security settings but I don't think this is the case with me, otherwise it wouldnt work at all. People have also mentioned the file being corrupt. I'm really not sure. Any help would be much appreciated.

UPDATE:

Excel is installed on the server and the exception occurs when trying to open the file.

Best Answer

Run> dcomcnfg

This will open Component Services and navigate to Console Root \Component Services\Computers\My Computer\DCOM Config\Microsoft Excel Application Right click Microsoft Excel Application and select Properties

Click on Identity Tab and check selection.

It works for me when select option - The interactive user

Please try, best luck!!