简体   繁体   中英

Loading assembly which was compiled programmatically fails

We try to compile source code at runtime and then add the resulting assembly to an AppDomain. But in the moment even loading the assembly fails:

string sourceCode = "using System;\r\n" +
                    "public class Program1{\r\n" +
                    "   public static void Main1(){\r\n" +
                    "     int i = 100;\r\n" +
                    "   }\r\n" +
                    "}";

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
Assembly[] assembliesOfCurrentDomain = AppDomain.CurrentDomain.GetAssemblies();

for (int runAssembliesInCurrDomain = 0; runAssembliesInCurrDomain < assembliesOfCurrentDomain.Length; runAssembliesInCurrDomain++)
{
    try
    {
        parameters.ReferencedAssemblies.Add(assembliesOfCurrentDomain[runAssembliesInCurrDomain].Location);
    }
    catch
    {
    }
}

// True - memory generation, false - external file generation
parameters.GenerateInMemory = false;
parameters.OutputAssembly = "D:\\temp\\123.dll";
parameters.IncludeDebugInformation = true;
parameters.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);

// True - exe file generation, false - dll file generation
parameters.GenerateExecutable = false;

CompilerResults results = provider.CompileAssemblyFromSource(parameters, sourceCode);
Assembly a = Assembly.Load("D:\\temp\\123.dll");

The last line throws an exception "An unhandled exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll". We have no idea what's going wrong there. We tried compiling this code with .Net Framework 2.0 and 4.5, with AnyCPU, x64, and x86. Always the same problem. Any ideas why this exception is be thrown?

You have to use the Assembly.LoadFrom method to load from a path. It will throw an exception that it is not recommended to do so but this exception is caught internally and programm succeeds.

From the MSDN article you should be passing in the long name of the assembly to Assembly.Load . For example:

string longName = "123, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
Assembly assem = Assembly.Load(longName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM