Junting Zhu
Junting Zhu

Reputation: 131

relative path of excel for c#

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.

Upvotes: 4

Views: 5092

Answers (3)

Maurizio Firmani
Maurizio Firmani

Reputation: 11

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.

Upvotes: 1

devuxer
devuxer

Reputation: 42374

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");

Upvotes: 0

Maximum Cookie
Maximum Cookie

Reputation: 437

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"));

Upvotes: 4

Related Questions