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.App
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
i think it is because xlApp.Workbooks.Open function only knows the absolute path,not likes File.Exists function
This is because Excel is another process than your .exe and the filename parameter in Workbook.Open has slightly different behavior than the filename parameter in File.Exists.
When you call File.Exists, the filename parameter may be either absolute or relative. If you use relative, it is relative to your .exe, so it will find the file placed in your .exe's folder.
When you create an Excel.Application object you get a new process with a separate working directory from your .exe. Note also that when you pass a relative filename path to the Workbook.Open function, it will not look for the file in Excel's working directory, but will instead use the default document folder for Office (typically "My Documents").
So, you should always use the absolute path in this scenario.
I found Matthew Watson's answer very helpful. It's also useful to set a relative path for Workbooks.Add() method. Here is my code for reference:
Excel.Application xlApp = new Excel.Application();
string path = "TestTemplete.xltx";
path = System.IO.Path.GetFullPath(path);
Workbook wb = xlApp.Workbooks.Add(path);