102

How do I find out what directory my console app is running in with C#?

John Sheehan
  • 77,456
  • 30
  • 160
  • 194

9 Answers9

179

To get the directory where the .exe file is:

AppDomain.CurrentDomain.BaseDirectory

To get the current directory:

Environment.CurrentDirectory
Hallgrim
  • 15,143
  • 10
  • 46
  • 54
16

Depending on the rights granted to your application, whether shadow copying is in effect or not and other invocation and deployment options, different methods may work or yield different results so you will have to choose your weapon wisely. Having said that, all of the following will yield the same result for a fully-trusted console application that is executed locally at the machine where it resides:

Console.WriteLine( Assembly.GetEntryAssembly().Location );
Console.WriteLine( new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath );
Console.WriteLine( Environment.GetCommandLineArgs()[0] );
Console.WriteLine( Process.GetCurrentProcess().MainModule.FileName );

You will need to consult the documentation of the above members to see the exact permissions needed.

wensveen
  • 783
  • 10
  • 20
Atif Aziz
  • 36,108
  • 16
  • 64
  • 74
5

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

410
  • 3,170
  • 8
  • 32
  • 36
4

In .NET, you can use System.Environment.CurrentDirectory to get the directory from which the process was started.
System.Reflection.Assembly.GetExecutingAssembly().Location will tell you the location of the currently executing assembly (that's only interesting if the currently executing assembly is loaded from somewhere different than the location of the assembly where the process started).

shA.t
  • 16,580
  • 5
  • 54
  • 111
Travis Illig
  • 23,195
  • 2
  • 62
  • 85
3

Let's say your .Net core console application project name is DataPrep.

Get Project Base Directory:

Console.WriteLine(Environment.CurrentDirectory);

Output: ~DataPrep\bin\Debug\netcoreapp2.2

Get Project .csproj file directory:
string ProjectDirPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\"));
Console.WriteLine(ProjectDirPath);

Output: ~DataPrep\

1

On windows (not sure about Unix etc.) it is the first argument in commandline.

In C/C++ firts item in argv*

WinAPI - GetModuleFileName(NULL, char*, MAX_PATH)

Jakub Kotrla
  • 257
  • 1
  • 6
0

Application.StartUpPath;

0

Use AppContext.BaseDirectory for .net5.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
0

Another solution is to use method Directory.GetCurrentDirectory:

string currentDirectory = Directory.GetCurrentDirectory();
Console.WriteLine("Working dir: " + currentDirectory);
p8R
  • 51
  • 2