C# – Cannot access excel file

cexcelinteropwindows-services

I'm developing a windows service, generating a report. This report has a template. This template is prepared in an excel file. This file is copied to the output folder.

While developing I launched the service like a console application and had no problems accessing this file.

Then I prepared a service installer. The service is installed under Local System account. So this excel template file is marked as content and copied to the installation directory together with the executable as well.

But when the service is launched excel appears to have no access to this file. The service is installed to c:\Program Files (x86)\Our Company\Service Name\. The target OS is Windows Server 2008. While testing I use Windows 7 and run into the same issue.

I use the following code to access excel.

using Excel = Microsoft.Office.Interop.Excel;    
//...
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
//the following line throws an exception
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(@"path"); 

I also tried to copy the excel template file to some temporary directory (where the service has the right to write – this is tested) and tryed to open it from there, but to no success (while this variant works good in a console application as well).

The error message sais:

Microsoft Office Excel cannot access the file /path/.
There are several possible reasons:

1. The file name or path does not exist.
2. The file is being used by another program.
3. The workbook you are trying to save has the same name as a currently open workbook.

How can I make the windows service access this excel template file? Or is there another alternative?

Best Answer

To safety run Office applications (Excel and others) under user service with Local system account you must know two important things: 1) In Windows Server 2008/2008 R2 you must manually create two folders: C:\Windows\system32\config\systemprofile\desktop
C:\Windows\SysWow64\config\systemprofile\desktop (for x64 version only) Without this folders you cannot correct run office Applications from Local SystemAccount

2) If you service is configured without desktop interaction then in the first time launched office application (Excel for example) freeze on user credentials dialog - you cannot see this window in this mode - to resolve this enable desctop interacting, switch to office window after you service run it and manually enter credeentials.

Other information there(use google translater to read).