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


i have trouble understande why i´m getting exception. have 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' not found 

well that´s why i´m checking file.exists, dont exception. how work, file.exists true, file still cannot found? if i´m using absolute path, it´s working. why? use without absolute path, ideas? thank you

edit: of course file.xls in same folder .exe -> that´s why (as expected) file.exists returning true. wanted make clear ;)

this happens because there 2 processes involved, each of has own current working directory (cwd).

your process (the 1 calling file.exists()) has cwd happens hold file you're using. excel has different cwd (probably location of excel executable) of course doesn't hold file.

you can fix using:

path = system.io.path.getfullpath(path); 

before passing path workbooks.open(path)

it might possible change excel's cwd calling macro using executeexcel4macro.

see here details: set current directory in excel.application via .net office pia


Comments