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?
An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. Assemblies take the form of executable (.exe) or dynamic link library (. dll) files, and are the building blocks of . NET applications.
. NET defines a binary file format, assembly, that is used to fully describe and contain . NET programs. Assemblies are used for the programs themselves as well as any dependent libraries.
LoadFrom(String) Loads an assembly given its file name or path.
С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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With