Search code examples
c#compact-framework.net-assembly

How to load an assembly from byte array in compact framework


I have legacy clients who use smart scanners with old windows mobile on them. As a result, I'm stuck developing in the compact framework for these smart devices. I am in the process of writing a class library which will provide a plugin type mechanism for an interface to the scanner hardware. I would like to be able to embed the third party assemblies from the scanner manufacturer as an embedded resource in the plugins DLL. I want to do this to avoid having to reflect over all of those third party DLL's when my plugin system is trying to find implementations of the interface for the plugins. Pretty strait forward. The issue is that with the embedded resource, I can get the bytes for the assembly, but System.Reflection.Assembly.LoadAssembly(byte[]) is not available in the compact framework. Only LoadAssembly(AssemblyName) and LoadAssembly(String). How can I load these assemblies at runtime from an embedded resource?

This is what I have now:

    protected void LoadEmbeddedAssemblies()
    {
        Assembly asm = Assembly.GetCallingAssembly();
        foreach (string resName in asm.GetManifestResourceNames())
        {
            if (resName.EndsWith(".dll"))
            {
                try
                {
                    //this is an embedded assembly
                    using (Stream s = asm.GetManifestResourceStream(resName))
                    {
                        if (s.Length > Int32.MaxValue) throw new IOException("The assembly is to large");
                        byte[] bytes = new byte[s.Length];                            
                        s.Read(bytes, 0, Convert.ToInt32(s.Length));

                        //Assembly.Load(bytes) <- Compact Framework sucks
                    }
                }
                catch (Exception e)
                {
                    Log(new LogMessageRaisedEventArgs("AScannerBase", "LoadEmbeddedAssemblies", "Exception encountered while loading embedded assembly", e.Message));
                }
            }
        }
    }

Solution

  • The Compact Framework doesn't support loading an assembly that way. Since the platforms the app is running on is unlikely to ever change on a given device, just determine the device type of the first run and extract the appropriate assemblies to the app folder, from that point on the loader will find them for you.