How do I find the application's path in a console application?
In Windows Forms, I can use Application.StartupPath
to find the current path, but this doesn't seem to be available in a console application.
How do I find the application's path in a console application?
In Windows Forms, I can use Application.StartupPath
to find the current path, but this doesn't seem to be available in a console application.
You have two options for finding the directory of the application, which you chose will depend on your purpose.
For anyone interested in asp.net web apps. Here are my results of 3 different methods
result
the app is physically running from "C:\inetpub\SBSPortal_staging", so the first solution is definitely not appropriate for web apps.
I use this if the exe is supposed to be called by double clicking it
I didn't see anyone convert the LocalPath provided by .Net Core reflection into a usable System.IO path so here's my version.
This will return the full "C:\xxx\xxx" formatted path to where your code is.
Assembly.GetEntryAssembly().Location
orAssembly.GetExecutingAssembly().Location
Use in combination with
System.IO.Path.GetDirectoryName()
to get only the directory.The paths from
GetEntryAssembly()
andGetExecutingAssembly()
can be different, even though for most cases the directory will be the same.With
GetEntryAssembly()
you have to be aware that this can returnnull
if the entry module is unmanaged (ie C++ or VB6 executable). In those cases it is possible to useGetModuleFileName
from the Win32 API:Probably a bit late but this is worth a mention:
Or more correctly to get just the directory path:
Edit:
Quite a few people have pointed out that
GetCommandLineArgs
is not guaranteed to return the program name. See The first word on the command line is the program name only by convention. The article does state that "Although extremely few Windows programs use this quirk (I am not aware of any myself)". So it is possible to 'spoof'GetCommandLineArgs
, but we are talking about a console application. Console apps are usually quick and dirty. So this fits in with my KISS philosophy.