I have a problem trying to execute a dynamic assembly in a given application domain. The assembly is building using System.Reflection.Emit.AssemblyBuilder
class as shown
// Utility method for building 'MathClient' assembly in memory.
public static void CreateMathClient(AppDomain domainForAssembly)
{
// Assembly name...
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "MathClient";
assemblyName.Version = new Version("1.0.0.0");
AssemblyBuilder assembly = domainForAssembly.DefineDynamicAssembly(
assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder module = assembly.DefineDynamicModule(
"MathClient", "MathClient.exe", false);
// Defining 'Program' class...
TypeBuilder programClass = module.DefineType(
"MathClient.Program",
TypeAttributes.Public | TypeAttributes.Class);
// Defining Main() method...
MethodBuilder mainMethod = programClass.DefineMethod(
"Main",
MethodAttributes.Public | MethodAttributes.Static,
null,
new Type[] { typeof(string[]) });
ILGenerator mainMethodILGenerator = mainMethod.GetILGenerator();
LocalBuilder aLocalVariable = mainMethodILGenerator.DeclareLocal(typeof(int), true);
mainMethodILGenerator.Emit(OpCodes.Ldc_I4, 10);
mainMethodILGenerator.Emit(OpCodes.Stloc, aLocalVariable); // a = 10
// List 'a' value...
mainMethodILGenerator.Emit(OpCodes.Ldstr, "a = {0}");
mainMethodILGenerator.Emit(OpCodes.Ldloc, aLocalVariable);
mainMethodILGenerator.Emit(OpCodes.Box, typeof(int));
Type consoleType = typeof(System.Console);
MethodInfo writeLineMethod = consoleType.GetMethod(
"WriteLine",
new Type[] { typeof(string), typeof(object) });
mainMethodILGenerator.Emit(OpCodes.Call, writeLineMethod);
mainMethodILGenerator.Emit(OpCodes.Ret);
// Bake 'Program' class type...
programClass.CreateType();
// Set Main() method as an entry point...
assembly.SetEntryPoint(mainMethod, PEFileKinds.ConsoleApplication);
// Optionally save to disk...
//assembly.Save("MathClient.exe");
}
When I'm trying to execute the assembly in a default application domain
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
// Create new assembly in memory...
CreateMathClient(currentDomain);
// Execute 'MathClient.exe' in the current domain...
currentDomain.ExecuteAssemblyByName(
"MathClient,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null");
Console.ReadLine();
}
the following exception is throwing
System.IO.FileNotFoundException was unhandled HResult=-2147024894 Message=Could not load file or assembly 'MathClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
However, if the assembly was preliminary saved to disk
// Optionally save to disk...
assembly.Save("MathClient.exe");
everything works perfectly fine.
Why can't I execute the assembly with ExecuteAssemblyByName()
?
Aucun commentaire:
Enregistrer un commentaire