Search code examples
c#console-application.net-core-3.1

GetCurrentDirectory() returns local path after deployed on server


Requirement: In my .Net Core console application, I use Directory.GetParent(Directory.GetCurrentDirectory()) to retrieve the current parent folder of where my template file is stored.

Issue: After deploying on server, when I manually run the exe by double clicking it works fine. But when I try to run it with batch or task scheduler, the above statement return by local computers path, instead of the path on server.

Server Details: OS: Windows Server 2012 R2 Standard

Error Stack: Error Message : Could not find document StackTrace : at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(String path, Boolean readWriteMode) at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(String path, Boolean isEditable, OpenSettings openSettings) at CV_Export.Program.SearchAndReplace(String TemplatePath, String NewDocumentPath) in C:\Siddharth\Demo Codes.Net Core Demo\CV Export with API\CV_Export\Program.cs:line 163 TIme : 7/21/2021 4:41:53 PM

This error was generated when I tried to run the exe through batch and the path on the error is of my local system.

Thank you in advance for your help.


Solution

  • By using Directory.GetParent(App.Domain.CurrentDomain.BaseDirectory) you can provide the relative path to the base directory of your application.

    When you are using Directory.GetCurrentDirectory() you are providing the path from where you are running the application, which can be for instance C:\Windows\System32, and the parent directory will be C:\Windows instead of the parent directory of your .net application.