我正在尝试使用 C# 代码提供程序从我的代码编译程序集。
当我使用 compilerResult.CompiledAssembly 访问已编译的程序集时,一切正常。但是,当我改为执行 Assembly.Load(path) 时,会出现以下异常:
System.IO.FileLoadException:无法加载文件或程序集“C:\Users\Name\Desktop\output.dll”或其依赖项之一。给定的程序集名称或代码库无效。(来自 HRESULT 的异常:0x80131047)
我究竟做错了什么?
这是代码:
[Test]
public static void CompileCodeIntoAssembly()
{
var code = "public class X { }";
var file = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "output.cs");
File.WriteAllText(file, code);
using (var provider = new CSharpCodeProvider())
{
var parameters = new CompilerParameters
{
GenerateInMemory = false, // we want the dll saved to disk
GenerateExecutable = false,
CompilerOptions = "/target:library /lib:\"" + typeof(Class2).Assembly.Location + "\"",
OutputAssembly = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "output.dll"),
};
parameters.ReferencedAssemblies.AddRange(new[]
{
"System.dll",
typeof(Class1).Assembly.Location,
});
var compilerResult = provider.CompileAssemblyFromFile(parameters, file);
if (compilerResult.Errors.Count > 0)
{
compilerResult.Errors.Cast<object>().ToDelimitedString(Environment.NewLine).Dump();
throw new Exception();
}
var assembly = Assembly.Load(parameters.OutputAssembly);
//var assembly = compilerResult.CompiledAssembly; // this method works
var type = assembly.GetTypes().Single(t => t.Name == "X");
}