Timothy Ghanem
Timothy Ghanem

Reputation: 1616

Assembly.Load .NET Core

I have an assembly that was dynamically generated using AssemblyBuilder.DefineDynamicAssembly, yet when i try to load it, i get the following error:

System.IO.FileNotFoundException: 'Could not load file or assembly 'test, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

This is the full code to reproduce:

var name = new AssemblyName("test");
var assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
var assembly2 = Assembly.Load(name);

I am using .NET Core 2.0, 2.1 and 2.2.

Can somebody please explain why this happens and any possible solutions?

Upvotes: 10

Views: 908

Answers (1)

Alieh S
Alieh S

Reputation: 170

Сause of error

You defined a dynamic assembly with the access mode AssemblyBuilderAccess.Run, which does not allow to save the assembly. Then, you try to load the assembly with the Load method of the Assembly class, which searches for a file.

Solution

If you want to work with a dynamic assembly in memory, you already got it. The next step is to define modules, types, and another with the help of other builders.

var moduleBuilder = assembly.DefineDynamicModule("test");
var typeBuilder = moduleBuilder.DefineType("someTypeName");
var type = typeBuilder.CreateType();
var instance = Activator.CreateInstance(type);

More information you will find in .NET API Docs.

Upvotes: 1

Related Questions