C# Excel.Workbooks.Open 路径问题
在编码时,我们一般都采用相对路径来读取文件或者图片等等,但是在Excel时却发生了意外,老是说找不到文件,
string path = "file.xls"; if (File.Exists(path)) { Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);//exception //... }
编译时你会发现File.Exists(path)是成功的,但是在Workbooks.Open(path)时报错了。
原因:前者判断是默认的Current Directory是Solution下的bin\Debug目录(如果你采用Debug模式),但是Excel的默认路径却不是,具体貌似在office.excel的安装目录下(未经核实)。
所以当我们试图Open(path)时就报错了,应为directory下没有那个文件,那么怎么解决呢,下面给出两个句子:
filepath = System.IO.Path.GetFullPath(filepath);//完整的路径名 string localPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);//定位到bin\Debug
其中filepath和上文的path一致
浙公网安备 33010602011771号