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

后端 未结 4 2025
感情败类
感情败类 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:31

    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.

提交回复
热议问题