Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relative path of excel for c#

Tags:

c#

excel

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.

like image 882
Junting Zhu Avatar asked Oct 21 '25 05:10

Junting Zhu


1 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"));
like image 169
Maximum Cookie Avatar answered Oct 23 '25 19:10

Maximum Cookie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!