Alex Rivera | Logout

Can a C# Multithreaded Application use separate WorkingDirectories per thread?

Asked 2013-06-13T22:32:42.823
13

In C# (.NET), can two threads running in the same application have DIFFERENT "WorkingFolders"??

As best I can tell, the answer would be "NO". I think the WORKING DIR is set by the PROCESS in Win32.. Am I wrong here?

According to the following test code, (as well the Win32 SetCurrentDirectory API call), this is NOT possible, but has anyone figured out a way to MAKE it possible?

using System;
using System.Threading;

public class TestClass {

  public  ManualResetEvent _ThreadDone = new ManualResetEvent(false);

  public static void Main() {
    Console.WriteLine(Environment.CurrentDirectory);

    Thread _Thread = new Thread(new ParameterizedThreadStart(Go));
    TestClass test = new TestClass();

    _Thread.Start(test);
    if(test._ThreadDone.WaitOne()) {
      Console.WriteLine("Thread done.  Checking Working Dir...");
      Console.WriteLine(Environment.CurrentDirectory);
    }
  }

  public static void Go(object instance) {
    TestClass m_Test = instance as TestClass;
    Console.WriteLine(Environment.CurrentDirectory);
    System.IO.Directory.SetCurrentDirectory("L:\\Projects\\");
    Console.WriteLine(Environment.CurrentDirectory);
    m_Test._ThreadDone.Set();
  }
}

I know SOMEONE out there has to have ran across this before!

Edit
Report

1 Answer

4

has anyone figured out a way to MAKE it possible?

It's simply not possible. You can't even have different working directories per App Domain.

The windows rule is: one Environment set per Process. Running in .NET won't change the basic rules.

Instead of that, if you experienced problem in loading assemblies, consider adding the corresponding folder to the PATH environment variable.

answered 2013-06-13T22:36:54.727

Your Answer