Loading C# assembly from MemoryStream: Bad IL format. How to correctly load fully in-memory assembly?


Using .NET Core 2.1 and Microsoft.CodeAnalysis.CSharp.Scripting 2.10.0 to dynamically compile to assembly and keep it in-memory. Then trying to load this assembly via AssemblyLoadContext getting

Bad IL format

How to correctly load fully in-memory assembly? What is the reason of this exception? I am missing to specify some metadata to the in-memory assembly? What are other most common cases then Bad IL format could occur?

This code example bellow produces the exception:

using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace ConsoleApp2
    class Program
        static async Task Main(string[] args)
            using (Stream stream = new MemoryStream())

                var compilation = CSharpCompilation.Create("a")
                    .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))

public static class C
    public static int M(int a, int b)
        return a+b;


                var results = compilation.Emit(stream);
                //results.Success is true here
                var context = AssemblyLoadContext.Default;
                Assembly a = context.LoadFromStream(stream);//<--Exception here.

Runtime exception details:

  Message=Bad IL format.
  Source=<Cannot evaluate the exception source>
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, Int32 iAssemblyArrayLen, IntPtr ptrSymbols, Int32 iSymbolArrayLen, ObjectHandleOnStack retAssembly)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromStream(Stream assembly, Stream assemblySymbols)
   at ConsoleApp2.Program.<Main>d__0.MoveNext() in C:\repos\sketches\ConsoleApp2\Program.cs:line 37
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ConsoleApp2.Program.<Main>(String[] args)
asked on Stack Overflow Dec 11, 2018 by Vinigas • edited Dec 11, 2018 by Vinigas

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0