Should I use AppDomain.CurrentDomain.BaseDirectory or System.Environment.CurrentDirectory?

I have two exe files in the same folder, I can run exe2 from a button in exe1. Today I was observing a customer over a remote (terminal services) session and exe2 failed to run 'File not found' error, yet exe1 was in the same directory when we checked. So should I be using AppDomain.CurrentDomain.BaseDirectory or System.Environment.CurrentDirectory?

Thanks


Solution 1:

If you want to find files in the same directory as your application, AppDomain.CurrentDomain.BaseDirectory is the correct choice.

Environment.CurrentDirectory is a value that can and will change throught the course of running your application. For instance, using default parameters, the OpenFileDialog in WinForms will change this value to the directory where the file was selected from.

Solution 2:

AppDomain.CurrentDomain.BaseDirectory returns the directory from where the current application domain was loaded.
System.Environment.CurrentDirectory returns the current system directory.
In your case AppDomain.CurrentDomain.BaseDirectory is the best solution.

Solution 3:

You should use AppDomain.CurrentDomain.BaseDirectory.

For example in a windows services application:

System.Environment.CurrentDirectory will return C:\Windows\system32

While

AppDomain.CurrentDomain.BaseDirectory will return [Application.exe location]

Another important factor to note is that AppDomain.CurrentDomain.BaseDirectory is a readonly property while the Environment.CurrentDirectory can be something else if necessary:

// Change the directory to AppDomain.CurrentDomain.BaseDirectory
Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;   

Solution 4:

As I understand it, you should use BaseDirectory. CurrentDirectory could change over the course of the program's execution.