Get application directory using C# Console Application?

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 still want to use Application.ExecutablePath in console application you need to:

  1. Add a reference to System.Windows.Forms namespace
  2. Add System.Windows.Forms to your usings section

    using System;
    using System.IO;
    using System.Windows.Forms;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string appDirectory = Path.GetDirectoryName(Application.ExecutablePath);
                Console.WriteLine(appDirectory);
            }
        }
    }
    

Also you can use Directory.GetCurrentDirectory() instead of Path.GetDirectoryName(Application.ExecutablePath) and thus you won't need a reference to System.Windows.Forms.

If you'd like not to include neither System.IO nor System.Windows.Forms namespaces then you should follow Reimeus's answer.


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.