Home » excel » relative path of excel for c#

relative path of excel for c#

Posted by: admin May 14, 2020 Leave a comment

Questions:

Hi I just had such this problem here. I am trying to use a relative path to link to an excel file within the same directory of the exe file itself.
When I use

Excel.Workbook wkbook = exapp.Workbooks.Open(@".\test.xlsx");

I put my exe file in the f drive. It turned out that the exe file altered the test.xlsx file in the C:\Users\\Documents folder(And also it somehow created the test.xlsx itself).
However when I use “.\xx.txt” or “xx.txt” , it worked perfectly well.

Can anyone tell me what to do? Thank you.

How to&Answers:

To get a filepath relative to the currently executing exe, you can use the following:

string exeDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Excel.Workbook wkbook = exapp.Workbooks.Open(System.IO.Path.Combine(exeDir, "test.xlsx"));

Answer:

One solution would be: don’t use relative paths. Here is some code to explicitly set the path:

var executableFolderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Excel.Workbook wkbook = exapp.Workbooks.Open(executableFolderPath + @"\test.xlsx");

Answer:

When you create a class instance of Excel.Application, the default path for files can be stored in its DefaultFilePath property; for example, these two lines set the default file path for the xlApp object to the current assembly’s default directory.

xlApp = new Excel.Application();
xlApp.DefaultFilePath = Environment.CurrentDirectory;

You can set every directory of your choice, by the way.