Oct 23
There may be times when you wish to temporarily load a .NET assembly to inspect it, but you don’t want the assembly to remain in your program’s memory taking up resources. Unfortunately, once your program loads an assembly, there is no way to unload it. The best way is to create a separate AppDomain, load the assembly into that AppDomain, then unload the AppDomain when you are finished.
The following sample code loads a .NET assembly from disk, displays the name of every type defined in the assembly, then unloads the assembly:
AppDomain appDomain = null; try { string path = @"C:myAssembly.dll"; byte[] buffer = File.ReadAllBytes( path ); appDomain = AppDomain.CreateDomain( "Test" ); Assembly assm = appDomain.Load( buffer ); Type[] types = assm.GetTypes(); foreach (Type type in types) { Console.WriteLine( type.FullName ); } } catch (Exception ex) { Console.WriteLine( ex.Message ); } finally { if (appDomain != null) AppDomain.Unload( appDomain ); }
[…] is Signed .NET Assembly FAQ – Part 1 Determine the Version of a Loaded .NET Assembly Read more… Share and […]
This doesn’t always work, I got an exception message indicating that “Could not load file or assembly” which was thrown by the appdomain.Load() statement.
Reading the bytes into the buffer went ok so the file is found. I think the problem is that IF the assembly that you are loading depends on other non-GAC assemblies and they are not in your execution path, then it would fail.
Attempting this, wherein one dll loads several others in this manner, fails with the error that the loading dll be ‘serializable’, so unless THAT can be achieved easily (seems very laborious as far as I can tell), this is not possible. Bring back COM I say. This kind of stuff was trivial.