How to get execution directory of console application
C#.NetFilepathC# Problem Overview
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.
C# Solutions
Solution 1 - C#
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.
Solution 2 - C#
Use this :
System.Reflection.Assembly.GetExecutingAssembly().Location
Combine that with
System.IO.Path.GetDirectoryName if all you want is the directory.
Solution 3 - C#
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.
Solution 4 - C#
Safest way:
string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
Solution 5 - C#
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");