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 ;)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With