0

I am reading an Excel file in the following way:

string path = @"C:\Users\myUserName\inputfile.xlsx";
Excel.Application app = new Application();
Excel.Workbook workbook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

I was wondering if there is any way I can give relative path instead of hard-coded absolute path. What I have in mind is to put the inputfile.xlsx in the same directory and do something like...

string path = @"inputfile.xlsx";  

But, it gives "COMException unhandled..", "inputfile.xlsx not found"

NGambit
  • 1,141
  • 13
  • 27

3 Answers3

2

use the following code to get the .exe location: ‫‪

string localPath = System.IO.Path.GetDirectoryName
‫‪(System.Reflection.Assembly.GetExecutingAssembly().Location‬‬)
elyashiv
  • 3,623
  • 2
  • 29
  • 52
  • Assuming the current directory was not changed by anything, such as an OpenFileDialog with RestoreDirectory false. Directory.GetCurrentDirectory() is safer. – Eric J. Aug 20 '12 at 16:08
  • 1
    GetCurrentDirectory is never safer – banging Aug 20 '12 at 16:11
  • Hmm... [120 upvotes](http://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in-net-in-a-console-app) can't be wrong! – Sumo Aug 20 '12 at 16:16
  • I realized I misread the OP's intent. He wants to find the path relative to the executable's location rather than relative to the current directory. +1. – Eric J. Aug 20 '12 at 17:02
1

You can use Directory.GetCurrentDirectory() to understand what your current directory is, if there is any doubt.

If Excel is not finding the file, chances are very good that you misunderstand what the current directory is. Construct the path relative to the directory returned by GetCurrentDirectory().

FYI, running the app stand-alone, in a debugger, and in a MS Test unit test will all set different current directories. The reason is that the executable is started from a different directory in each case.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • I found the 'current directory' as you suggested but putting the file there and string path = @"...\inputfile.xlsx"; or string path = @"inputfile.xlsx"; doesn't seem to work – NGambit Aug 20 '12 at 16:36
0

Make sure the excel file is in the same folder as the executable, or alternatively make sure that the relative path is correct, relative to the directory containing the executable.

If the excel file is included in your project, you could also right click on it in the solution explorer, click on properties, and set the "Copy to Output Directory" to something like "Copy always". This will cause the file to be placed in the projects output directory. A relative path would then only include the name of the file.

Seth Flowers
  • 8,990
  • 2
  • 29
  • 42