Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get application directory using C# Console Application?

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?

like image 739
a1204773 Avatar asked Oct 13 '12 16:10

a1204773


2 Answers

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.

like image 172
WhoIsRich Avatar answered Sep 22 '22 13:09

WhoIsRich


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
like image 25
Reimeus Avatar answered Sep 23 '22 13:09

Reimeus