Why return BAD IL FORMAT to load assembly from wcf

2019-08-04 00:16发布

问题:

I want to load this Class library :


namespace ClassLibrary1
{
    public class Class1
    {
        public Class1()
        {
        }
        public static int Sum(int a, int b)
        {
            return a + b;
        }
    }
}

I have a wcf service which returns to me a byte[] array (ClassLibrary1) i can not load this assembly

static void Main(string[] args)
{
    FileTransferService.ApplicationHostServiceClient client = new FileTransferService.ApplicationHostServiceClient();

    FileTransferService.AssemblyPackage[] asmbs = client.GetFile();
    //var newDomain = AppDomain.CreateDomain("FooBar", null, null);
    foreach (FileTransferService.AssemblyPackage item in asmbs) 
    {
        byte[] mybuffer = item.Buffer;
        new AssemblyLoader().LoadAndCall(mybuffer);
    }
}

public class AssemblyLoader : MarshalByRefObject
{
    public void LoadAndCall(byte[] binary)
    {
        Assembly loadedAssembly = AppDomain.CurrentDomain.Load(binary);
        object[] tt = { 3, 6 };
        Type typ = loadedAssembly.GetType("ClassLibrary1.Class1");
        MethodInfo minfo = typ.GetMethod("Sum", BindingFlags.Public);
        int x = (int)minfo.Invoke(null, tt);
        Console.WriteLine(x);
    }
}

Error return to me in this method : Assembly loadedAssembly = AppDomain.CurrentDomain.Load(binary);

ERROR:

BADIMAGEFORMAT EXCEPTION
Could not load file or assembly '4096 bytes loaded from Client2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.

EXCEPTION :

Bad IL format

i have googling this kind of error but no exact solution. i want to load my assembly using AppDomain.

回答1:

The first thing to check in this scenario is that the byte[] you received is exactly identical to the original, as there are many ways of making a mess of handing a chunk of binary. Perhaps write the file to disk (File.WriteAllBytes) and your favourite file compare tool, or use something like base-64 or a sha-1 hash to validate the contents. I strongly suspect you'll find it isn't the same.



回答2:

Since this is one of the first results when googling Bad IL format I thought I'd explain what that means.

BadImageFormatException is thrown when the Intermediate Language of the assembly is invalid. In the case of this question it was due to WCF truncating it, in my case a .Net Framework dll was corrupted by a failing harddrive.

So in general the problem will exist at the byte level, for this problem in general I'd debug it with these steps:

  1. Recompile everything possible
  2. Run sfc on the system
  3. Run chkdsk
  4. Compare the byte streams of assemblies (do this first if you're loading an assembly from a byte stream)