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

后端 未结 4 2028
感情败类
感情败类 2021-01-12 05:11

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         


        
4条回答
  •  广开言路
    2021-01-12 05:20

    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

提交回复
热议问题