tags:

views:

19

answers:

2

hi,

i created a appDomain in my application which base directory is different to my application directory, but it is under the application. i loaded an assembly in the created domain and create object instance from that domain. then i try to execute the method of the object. but i observe an odd behavior.

    public class Class1 : MarshalByRefObject
{
    public void action()
    {
        Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory);
        TextReader sr = new StreamReader(File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + "\\test.txt"));

        Console.WriteLine(sr.ReadToEnd());
    }
}

there's a 'test.txt' file under the appDomain.BaseDirectory. but if i only give the file name, the application still try to search the file from the application execution directory and failed to find the file.

how can i make sure the code executed in another domain is using the base directory as the default search path.

A: 

perhaps you need to use one of the overloaded CreateDomain methods and specify the Base Directory. The following works for me:

AppDomain domain = AppDomain.CreateDomain("MyDomain", AppDomain.CurrentDomain.Evidence, "C:\\Projects\\ConsoleApplication1\\ClassLibrary1\\bin\\Debug\\", ".", true);
ObjectHandle o = domain.CreateInstanceFrom("ClassLibrary1.dll", "ClassLibrary1.Class1");
AppDomain.Unload(domain); 

In my code your action method implementation was moved to the constructor.

Tim Carter
sure i have set the base directory parameter. in your sample, you used the debug directory, and the debug application will be executed under the debug directory, so you cannot see any difference.
davidshen84
please note that the directory where i run the application that creates this app domain is C:\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\. I am assigning the base directory to the location of the assembly which contains the code you supplied. I could put this assembly in any directory and it will still work, as long as the test.txt file is in the same directory.
Tim Carter
A: 

The current directory of the process as maintained by Windows (Environment.CurrentDirectory) is not affected by the AppDomainSetup. It only affects where the CLR will look for assemblies. Changing CurrentDirectory will change it process-wide, surely that's not what you want.

Work with full path names, like you do in your snippet.

Hans Passant
thanks for the advise :)
davidshen84
@david - read this: http://blog.stackoverflow.com/2010/10/vote-early-vote-often/
Hans Passant