我们尝试在运行时编译源代码,然后将生成的程序集添加到 AppDomain。但此刻,即使加载程序集也失败了:
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");
最后一行抛出异常“mscorlib.dll 中发生了类型为‘System.IO.FileLoadException’的未处理异常”。我们不知道那里出了什么问题。我们尝试使用 .Net Framework 2.0 和 4.5、AnyCPU、x64 和 x86 编译此代码。总是同样的问题。有什么想法为什么会抛出这个异常吗?
最佳答案
您必须使用 Assembly.LoadFrom
方法从路径加载。它会抛出一个异常,不建议这样做,但该异常在内部被捕获并且编程成功。
关于c# - 加载以编程方式编译的程序集失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940620/