Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel: can only open file if using absolute path, why?

Tags:

c#

.net

file

excel

I have some trouble to understande why I´m getting an exception. I have something like this:

string path = "file.xls";
if (File.Exists(path))
{
  Excel.Application xlApp = new Excel.Application();
  Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path); //exception
  //...
}

Exception:

Unhandled Exception: System.Runtime.InteropServices.COMException: 'file.xls' could not be found

Well that´s why I´m checking with File.Exists, so I dont get this exception. So how does this work, File.Exists is true, but the file still cannot be found? If I´m using an absolute path, then it´s working. Why? I would like to use this without the absolute path, any ideas? Thank you

Edit: of course the file.xls is in the same folder as my .exe -> that´s why (as expected) File.Exists is returning true. Just wanted to make this clear ;)

like image 335
sabisabi Avatar asked May 06 '13 08:05

sabisabi


1 Answers

This happens because there are two processes involved, each of which has their own Current Working Directory (CWD).

Your process (the one calling File.Exists()) has a CWD which happens to hold the file that you're using. Excel has a different CWD (probably the location of the Excel executable) which of course doesn't hold the file.

You can fix this by using:

path = System.IO.Path.GetFullPath(path);

before passing path to Workbooks.open(path)

It might be possible to change Excel's CWD by calling a macro using ExecuteExcel4Macro.

See here for some details: Set Current Directory in Excel.Application via .NET Office PIA

like image 116
Matthew Watson Avatar answered Sep 22 '22 18:09

Matthew Watson