4

I have a c# application A that starts another c# application B like so:

string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string path = baseDir + "Programs\\Logging\\";
Process logger = new Process();
logger.StartInfo.FileName = System.IO.Path.Combine(path, "Logger.exe");
logger.Start();

In the Logger.exe I do the following:

string dir = Directory.GetCurrentDirectory();

But it tells me that dir is the directory of the original program A that launched it, not its own directory (Programs\Logging)

Why is this??

SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
Harry Boy
  • 4,159
  • 17
  • 71
  • 122
  • 1
    My guess it's that it's running under the same AppDomain of the app launching the `logger` process. Have you tried changing the use of `Directory.GetCurrentDirectory()` to `Environment.CurrentDirectory`? [see here](http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory(v=vs.110).aspx) – Mario J Vargas Jun 19 '14 at 17:01
  • 1
    Can you fix this line first: `string dir = string dir = Directory.GetCurrentDirectory(););` – B.K. Jun 19 '14 at 17:02
  • 1
    GetCurrentDirectory must be tied into the AppDomain that launched the process. Not sure but that's what I am guessing. – Mike Cheel Jun 19 '14 at 17:02
  • Environment.CurrentDirectory returns the same result. Thanks for the help :) – Harry Boy Jun 19 '14 at 17:09

2 Answers2

6

That is the correct directory. It's the working directory where you launched that process from. If you want to change it, do it like:

string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string path = baseDir + "Programs\\Logging\\";
Process logger = new Process();
// Here's the deal
logger.StartInfo.WorkingDirectory = path;
logger.StartInfo.FileName = System.IO.Path.Combine(path, "Logger.exe");
logger.Start();
Jcl
  • 27,696
  • 5
  • 61
  • 92
  • In .NET Core when I compile to an exe and run it via the commandline, this sets some crazy Temp directory under AppData\Local. -- It works when you run from Visual Studio, but not when distributed. – BrainSlugs83 Sep 11 '19 at 22:30
  • @BrainSlugs83 what I changed was setting the `WorkingDirectory` on the process (that's what the question was about)... in NET Core you don't have an AppDomain (you do, but it's from the bootstrapper process), so to find out the "launching directory" you have to do it differently (most likely extracting it from the Uri on the executing assemblies's CodeBase, but your mileage may vary) – Jcl Sep 12 '19 at 06:58
1

Per MSDN, The current directory is distinct from the original directory, which is the one from which the process was started.

http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory(v=vs.110).aspx

So, it's doing the right thing.

B.K.
  • 9,982
  • 10
  • 73
  • 105