Home All Groups Group Topic Archive Search About

Assembly.Load from byte[]

Author
17 Jul 2006 5:16 PM
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[]...

Author
17 Jul 2006 5:55 PM
David Browne
<buttslap***@gmail.com> wrote in message
Show quote
news:1153156587.253339.178260@m79g2000cwm.googlegroups.com...
> 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
Author
17 Jul 2006 6:19 PM
buttslapper
Thanks

AddThis Social Bookmark Button