eugeneK
eugeneK

Reputation: 11116

How to get execution directory of console application

I tried to get the directory of the console application using the below code,

Assembly.GetExecutingAssembly().Location

but this one gives me where the assemble resides. This may be different from where I executed the application.

My console application parses logs with no parameters. It must go to the logs/ folder inside of the executable's folder or if I give it a path to logs/ it parses it.

Upvotes: 83

Views: 131484

Answers (6)

DiamondDrake
DiamondDrake

Reputation: 1159

If google takes in here in 2024 using dotnetcore 8.0, the current way is

System.AppContext.BaseDirectory

Upvotes: 1

MikeT
MikeT

Reputation: 2663

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.

Upvotes: 20

Donovan Phoenix
Donovan Phoenix

Reputation: 1511

Here is a simple logging method

using System.IO;
private static void logWrite(string filename, string text)
{
    string filepath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + filename;

    using (StreamWriter sw = File.AppendText(filepath))
    {
        sw.WriteLine(text);
        Console.WriteLine(text);
    }
}

Usage:

logWrite("Log.txt", "Test");

Upvotes: 4

dtsg
dtsg

Reputation: 4468

Safest way:

string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

Upvotes: 8

Sunny
Sunny

Reputation: 3295

Use this :

System.Reflection.Assembly.GetExecutingAssembly().Location

Combine that with

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

Upvotes: 53

Stefan
Stefan

Reputation: 14870

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.

Upvotes: 129

Related Questions