I'm trying to compile an assembly from my code with C# code provider.
When I access the compiled assembly with compilerResult.CompiledAssembly, everything works. However, when I instead do Assembly.Load(path), I get the following exception:
System.IO.FileLoadException : Could not load file or assembly 'C:\Users\Name\Desktop\output.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
What am I doing wrong?
Here's the code:
[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");
}