Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these ways of getting current directory?

Tags:

c#

They all give the same result, the location of folder that contains the exe that is being executed. I am sure there are no good or bad methods in the .net BCL. They are all appropriate in particular circumstances. Which one is appropriate for which scenario?

var appBaseDir = AppDomain.CurrentDomain.BaseDirectory;  var currentDir = Environment.CurrentDirectory;  var dir = Directory.GetCurrentDirectory();  var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 
like image 538
Foo Avatar asked Sep 10 '13 19:09

Foo


1 Answers

They all give the same result

They certainly don’t. currentDir and dir both give you the current working directory – i.e. by default the directory your executable was run from (but it can be changed during the execution).

By contrast, appBaseDir and path get the directory which contains the executing assembly’s file.

To illustrate how they differ, consider that you have an executable which sits in C:\bar\baz.exe. Now I can execute the application by entering the following chain of commands in a terminal:

$ md C:\foo $ cd C:\foo $ ..\bar\baz.exe 

Now the current working directory is C:\foo but the application’s base directory is C:\bar. There exist analogous means of setting the working directory for other methods of launching an application (e.g. via a shortcut icon or programmatically, such as via Process.Start).

Still, the framework provides different ways of accessing this information:

Environment.CurrentDirectory quite directly conveys the meaning that the execution environment (an environment variable) is queried. Directory.GetCurrentDirectory() may actually do the same internally (I have no idea) but it encapsulates this, and rather focuses on providing the user with a logical API for querying information about directories.

AppDomain.CurrentDomain has information about the current AppDomain (roughly, the executable). Part of that information is, logically, the AppDomain’s path. By contrast, System.Reflection.Assembly gives you general information about assembles – these represent any kind of binary objects in .NET, including DLLs and EXEs. GetExecutingAssembly in particular returns the currently executed assembly. And you can get its path again by querying its Location property, which gives the physical path of an assembly file.

like image 87
Konrad Rudolph Avatar answered Oct 10 '22 00:10

Konrad Rudolph