How to load an assembly from a location on disk at runtime

by adrian.tosca 27. September 2008 09:49

Let's say there is an assembly in a certain location on disk and should be loaded at run time. Possible uses for these are: loading external addins for an application, meta information tools etc. How to do this? Well the first idea is to use Assembly.Load(fileName). Unfortunately this overload of the Load method take only an assembly name string, not a file path and can be used only if the assembly is in the same path as the calling assembly. The following will load the TestAddIn.dll assembly from the same location as the calling assembly:

Assembly testAddIn = Assembly.Load("TestAddIn");

 

If one tries to pass the full file name to the method, for example:

Assembly testAddIn = Assembly.Load(
    @"c:\AssemblyLoadSolution\AssemblyLoad\AddIns\TestAddIn.dll");

 

The following FileLoadException will be thrown: "Could not load file or assembly 'file' or one of its dependencies. The given assembly name or codebase was invalid."

The solution is to use another overload of the method Assembly.Load(AssemblyName assemblyRef). The AssemblyName describes the assembly in full including version and strong name. But for a simple use you only need to use the Name and CodeBase properties:

AssemblyName name = new AssemblyName("TestAddIn");
name.CodeBase = @"c:\AssemblyLoadSolution\AssemblyLoad
    \AddIns\TestAddIn.dll";
Assembly testAddIn = Assembly.Load(name);

 

The CodeBase property needs to be set to the full file path of the assembly. The only catch is that the application will need permissions to the folder where the application is loaded. This might be an additional issue on web applications.

Tags: , , ,

Programming

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

RecentComments

Comment RSS

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar