views:

221

answers:

3

Hello Devs,

How can I tell my .NET application where to look for a particular assembly which it needs (other than the GAC or the folder where the application runs from)? For example I would like to put an assembly in the user's Temp folder and have my application know that the referenced Assembly is in the temp folder.

Thanks

+3  A: 

See this discussion for some of the issues involved:

http://bytes.com/topic/c-sharp/answers/248203-dynamic-assembly-loading

Basically, you cannot change the appbase of an appdomain after it has been created. You must specify it as part of the configuration before creating a new one, which wont help you in the default appdomain.

If the assembly you want to load is in a directory beneath the current appbase then you can add its relative path using the AppendPrivatePath(relativePath), and then use Assembly.Load - the runtime will probe the subdirectories for you. This is the best/easiest way to handle it.

Robert Harvey
Thank you, just as a note I do not need to load it dynamically. I am referencing the assembly in my project. But when I deploy that application, I want the application to know that the referenced assembly will be in the temp folder
GX
+2  A: 

System.Reflection.Assembly.LoadFrom(myFile);

http://msdn.microsoft.com/en-us/library/1009fa28.aspx

Another alternative is to handle Assembly resolve events yourself as in this StackOverflow question: http://stackoverflow.com/questions/1373100/how-to-add-folder-to-assembly-search-path-at-runtime-in-net

RichAmberale
+2  A: 

you can use the AppDomain.AssemblyResolve event to add custom Assembly Resolvers. This allows you to point at other directories or even databases to get assemblies as needed.

I have even used similar code to download assemblies from a database and store in IsolatedStorage. The file name as a hash of the full Assembly name. Then the database would only need to download on the first time you resolve and all future resolutions will be served by the file system. The best about about the AssemblyResolve event is you can use it Type.GetType() and the built in Serializers.

static string lookupPath = @"c:\otherbin";

static void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += 
        new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

static Assembly CurrentDomain_AssemblyResolve(object sender, 
                                              ResolveEventArgs args)
{
    var assemblyname = args.Name.Split(',')[0];
    var assemblyFileName = Path.Combine(lookupPath, assemblyname + ".dll");
    var assembly = Assembly.LoadFrom(assemblyFileName);
    return assembly;
}
Matthew Whited