How to get execution directory of console application

Scott Hanselman has a blog post with the following:

using System;
using System.Diagnostics;
using System.IO;
 
namespace testdir
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"Launched from {Environment.CurrentDirectory}");
            Console.WriteLine($"Physical location {AppDomain.CurrentDomain.BaseDirectory}");
            Console.WriteLine($"AppContext.BaseDir {AppContext.BaseDirectory}");
            Console.WriteLine($"Runtime Call {Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)}");
        }
    }

which he uses in .NET Core 3.1, however, I'm running .NET 4.8 and it's working for me.


Use Environment.CurrentDirectory.

Gets or sets the fully qualified path of the current working directory.
(MSDN Environment.CurrentDirectory Property)

string logsDirectory = Path.Combine(Environment.CurrentDirectory, "logs");

If your application is running in c:\Foo\Bar logsDirectory will point to c:\Foo\Bar\logs.


Use this :

System.Reflection.Assembly.GetExecutingAssembly().Location

Combine that with

System.IO.Path.GetDirectoryName if all you want is the directory.

Tags:

C#

.Net

Filepath