Assembly.Load from byte[]

B

buttslapper

Hi,

Is it possible to load an assembly from a byte[] and make the framework
use this assembly instead of trying to locate them on disk..

Example :
My projet has a reference to the ESI.Framework assembly.

Assembly.Load(EmbeddedData.ESI.Framework);
ESI.Framework.Console c = new ESI.Framework.Console();

How can I bind the explicit reference that I added to my projet, to the
assembly loaded from my byte[]...
 
D

David Browne

Hi,

Is it possible to load an assembly from a byte[] and make the framework
use this assembly instead of trying to locate them on disk..

Example :
My projet has a reference to the ESI.Framework assembly.

Assembly.Load(EmbeddedData.ESI.Framework);
ESI.Framework.Console c = new ESI.Framework.Console();

How can I bind the explicit reference that I added to my projet, to the
assembly loaded from my byte[]...

Yes. You can add a custom AssemblyResolveEventHandler for your AppDomain.
If .NET can't find a referenced assembly in the normal places, it will call
any registered AssemblyResolveEventHandlers and give them the opportunity to
find and load the target assembly.

The only thing to be careful of is that you must add the ResolveEventHandler
before the target assembly is needed. In practice this means that the class
that holds your Main method cannot directly invoke any type in the target
assembly. However you Main method can call another type in the same
assembly which references the target assembly.

EG

class Program
{
static void Main(string[] args)
{
AppDomain myApp = AppDomain.CurrentDomain;
myApp.AssemblyResolve += new ResolveEventHandler(LoadMyLib);

Startup.Run(); //Startup can use MyLib


}

static System.Reflection.Assembly LoadMyLib(object sender,
ResolveEventArgs args)
{
Console.WriteLine(args.Name);
if (args.Name == "MyLibName, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null")
{
byte[] assemblyBytes =
System.IO.File.ReadAllBytes(@"C:\whatever\MyLibName.dll");
return System.Reflection.Assembly.Load(assemblyBytes);
}
else
{
return null;
}
}
}

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top