Cannot open Excel file in C#
Asked Answered
F

4

12

I have the following C# function in my project, which is supposed to open and return an existing Excel workbook object:

Application _excelApp;

// ...

private Workbook OpenXL(string path, string filename)
{
    try
    {
        if (_excelApp == null)
        {
            _excelApp = new Application();
        }

        Workbook workBook = _excelApp.Workbooks.Open(path + filename,   // Name
                                                     0,                 // Do not update links
                                                     true);             // Open read-only

        return workBook;
    }
    catch (Exception e)
    {
        _excelApp = null;
        throw new ArgumentException("Error opening " + path + filename, e);
    }
}

But when I run it with "C:\" and "scratch.xlsx", the Open() call throws the following error:

Microsoft Excel cannot access the file 'C:\scratch.xlsx'. There are several possible reasons:

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

The file and path does exist: I have copied the path from the error message and pasted it into a command window and the file loads up in Excel. The file is not locked: Excel can open it fine but my program cannot, even straight after a reboot. I am not trying to save it, I am trying to open it so the last option is irrelevant.

I am at a loss to understand why this simple piece of code is not working. Any suggestions would be hugely appreciated.

[edit] I have now tried opening that file from my personal network drive (M:) and from a USB stick. All to no avail.

The application is actually a Windows service, running under the local system account and generating reports. It currently write CSV reports with no access problems whatsoever. I am now trying to get it to open an excel file as a template report and fill in various fields. It is when opening the Excel file that it fails. I am thinking that the administrator account option everyone is suggesting is a red herring since it can write CSV files wityh no problem. [/edit]

--- Alistair.

Feat answered 8/7, 2013 at 15:46 Comment(5)
Try running as administrator? Does the user account have read permissions on the file?Footlights
Are you or c# escaping the ``?Mareah
Never join paths like path + filename; use Path.Combine(path, filename) instead!!Hindward
Which Excel Interop did you use? Is it the one correct for Excel 2007 or above?Hindward
Marco, I am using version 14.0.0.0 of the interop (C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Excel.dll)Feat
F
38

I found the following page:

http://social.msdn.microsoft.com/Forums/en-US/b81a3c4e-62db-488b-af06-44421818ef91/excel-2007-automation-on-top-of-a-windows-server-2008-x64

Where it says that...

it’s not supported to automate office products UI less. It seems that Windows Server 2008 and Excel 2007 enforce the given statement.

The questioner then describes exactly the situation I am in with a Windows Service that cannot open an Excel file, although the same code in a command-line program has no problem.

The response advises to create the following folder:

Windows 2008 Server x64: C:\Windows\SysWOW64\config\systemprofile\Desktop

Windows 2008 Server x86: C:\Windows\System32\config\systemprofile\Desktop

I have tried this and it worked a treat! Can anyone explain why it is needed and any downsides?

Thanks,

--- Alistair.

Feat answered 9/7, 2013 at 11:28 Comment(10)
Yes. I have the same problem. And your solution works for me too. But why?Cormophyte
No idea why, I have not found any reason for it and had forgotten completely about it. It will probably trip me up again when we migrate to new hardware soon!Feat
no idea why this works but I can confirm its just saved me while on Sever 2008 & office 2010Durango
Yes, I had to migrate to a new hw and it was helpful again, one forgets this stuff easilyPseudohermaphroditism
I'm getting a "user41013" tattoo in my chest. Works like a charm. Turns out, I unknowingly had that folder in my dev machine (so it worked), but I didn't have it in the deploy machine. Thanks a lot!Breast
same here. creating those folders did the work. thanks so much!Juliannjulianna
Just found this post a second time, fix it for my old Windows 7 system, then had to do it again after upgrading to Windows 10. However with windows 10 I had to set the Permissions for the "Everyone" user to full access on both folders before it would work.Counterweight
wow.. just wow, this finally solved my problem. but what's the explanation behind this sorcery??Kishke
I would assume that this folder makes the server think it is a desktop.Feat
this...smashed my head against my keyboard for a solid 2 hours, found this, problem solved!Weingartner
E
4

Run the program as admin, the C:/ cannot be accessed by a program unless the user is running as admin. You can make your program prompt the user it must be run as admin by altering the ApplicationManifest: How do I force my .NET application to run as administrator?

Enravish answered 8/7, 2013 at 15:49 Comment(7)
I'd also add that your code is working as expected, there is nothing wrong with your code.Datary
I'll second that, I see no problems with it assuming all the classes do what I expect they do.Enravish
It was originally accessing C:\Reports\. I changed the path to C:\ to make it simpler!Feat
If you have a partition like a D:\ drive or a mounted drive like F:\ and this is just a test/you can't be bothered to edit your app-manifest, use one of those drives instead.Enravish
@user41013: did you try merging path with Path.Combine as I suggested above?Hindward
Yes, using Path.Combine() now, thanks. I have tried putting the file on my network (M:) drive and it said it could not find it. I have put it on a memory stick and get the same 'Cannot access the file' error as above. I will now try running as administrator, although it galls me to have to do it!Feat
This application is part of a windows service that generates report files. It does this all the time, writing CSV files with no problems. This one new report uses an existing excel file and just updates certain fields. All I want to do is open the *#@%$! file. I have changed it to run under my own account since I am a local administrator but it still fails. I don't have the admin password itself and do not know if our SysAdmin will tell me it. I don't see why any program should need it open an Excel document!Feat
E
4

I was running into the same issue and I have investigated infomation about "registry hack".

After all, I found another solution that changes no registry values and everything works on properly.

This solution is ...

・Windows 2008 Server x64

Please make this folder.

  C:\Windows\SysWOW64\config\systemprofile\Desktop

・Windows 2008 Server x86

Please make this folder.

 C:\Windows\System32\config\systemprofile\Desktop

...instead of dcomcnfg.exe.

This operation took away office automation problems in my system.

A Desktop folder seems to be necessary in the systemprofile folder to open file by Excel.

It disappears from Windows2008, Windows2003 had the folder, and I think it cause this error.

I think it is safer than "registry hack".

If you try this solution, please let me know results.

Emissivity answered 17/6, 2015 at 13:20 Comment(1)
I had the folder, but I needed to grant correct permissions on it.Hanks
S
0

I had this issue today.

Surprisingly, it seems that the error occurred when the application was run as Administrator.

After we moved to Windows 10, some things (mainly related to IIS) would only work if running Visual Studio as Administrator, so it quickly became a habbit to start VS as Administrator.

The solution was to NOT run the application as Administrator.

This might be related to how our work environments are set up, but I thought it was worht sharing, if anyone else experiences the same issue, and the other solutions don't work for them either.

Sama answered 24/6, 2020 at 13:42 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.