Excel:如果使用绝对路径只能打开文件,为什么?

sab*_*abi 7 .net c# excel file

我有一些麻烦要说明为什么我得到一个例外.我有这样的事情:

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

例外:

Unhandled Exception: System.Runtime.InteropServices.COMException: 'file.xls' could not be found
Run Code Online (Sandbox Code Playgroud)

这就是为什么我要检查File.Exists,所以我没有得到这个例外.那么这File.Exists是如何工作的,是真的,但文件仍无法找到?如果我使用绝对路径,那么它正在工作.为什么?我想在没有绝对路径的情况下使用这个,有什么想法吗?谢谢

编辑:当然file.xls和我的文件夹在同一个文件夹中.exe- >这就是为什么(正如预期的那样)File.Exists返回true.只是想明确这一点;)

Mat*_*son 15

发生这种情况是因为涉及两个进程,每个进程都有自己的当前工作目录(CWD).

您的进程(一个调用File.Exists())有一个CWD,它碰巧保存您正在使用的文件.Excel具有不同的CWD(可能是Excel可执行文件的位置),当然不包含该文件.

您可以使用以下方法解决此问题

path = System.IO.Path.GetFullPath(path);
Run Code Online (Sandbox Code Playgroud)

path去之前Workbooks.open(path)

也许可以通过调用宏来更改Excel的CWD ExecuteExcel4Macro.

有关详细信息,请参阅此处:通过.NET Office PIA在Excel.Application中设置当前目录