7

I have an ASP.Net Core 3.1 solution that uses a Docker Compose file as its startup project. Calling the method Directory.GetCurrentDirectory() from anywhere in the code returns the string /app, which is weird as I was expecting this string to include /bin/Debug/netcoreapp3.1 or (Release if I build the code in release mode). If I go into the docker container that runs the code, the executing code is located at /app/bin/Debug/netcoreapp3.1.

What is going on?

yesman
  • 7,165
  • 15
  • 52
  • 117
  • You shouldn't rely on the current directory being the location of your app, that can be changed in code to anything. See here for better ways to do that https://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in-a-net-console-application. Also, why do you need the directory? Perhaps there's a better way to solve the problem you have. – DavidG Dec 16 '20 at 13:20
  • 6
    The "current directory" is the directory that the *user* is in when they launch your application. It's useful so that the user can run `path/to/yourapp.exe somefile`, where `somefile` is located in their current directory, and you can find that file to open it. You really can't rely on it being set to anything in particular, and there's no guarantee that it's set to the directory containing your executable. If you want to find the directory containing your executable, use e.g. `Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)` – canton7 Dec 16 '20 at 13:22
  • 1
    @DavidG I have a file that I have set to `Copy to Output Directory - Copy Always`, and need to access it from my code. The path can vary, considering I can build the code in both release mode and debug mode. – yesman Dec 16 '20 at 13:32
  • Thanks @canton7 , this solved my issue. – yesman Dec 16 '20 at 14:06

1 Answers1

6

Thanks to Canton7 in the comments above I figured out that you should call Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) instead.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
yesman
  • 7,165
  • 15
  • 52
  • 117