I found something on google but it not working on C# Console Application
What I found:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
How I can get application directory using c# Console Application?
BEWARE, there are several methods and PITFALLS for paths.
What location are you after? The working directory, the .EXE directory, the DLLs directory?
Do you want code that also works in a service or console application?
Will your code break if the directory has inconsistent trailing slashes?
Lets look at some options:
Application.ExecutablePath
Requires adding a reference and loading the Application namespace.
Directory.GetCurrentDirectory
Environment.CurrentDirectory
If the program is run by shortcut, registry, task manager, these will give the 'Start In' folder, which can be different from the .EXE location.
AppDomain.CurrentDomain.BaseDirectory
Depending on how it's run effects whether it includes a trailing slash. This can break things, for example GetDirectoryName() considers no slash to be a file, and will remove the last part.
Either of these are my recommendation, working in both Form and Console applications:
var AssemblyPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
or
var AssemblyPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
When used in a main program, both are indentical. If used within a DLL, the first returns the .EXE directory that loaded the DLL, the second returns the DLLs directory.
Application is not available for Console Applications, it's for windows forms.
To get the working directory you can use
Environment.CurrentDirectory
Also to get the directory of the executable, you could use:
AppDomain.CurrentDomain.BaseDirectory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With