Weird Assembly.Load error trying to load assembly compiled with C# code provider
Asked Answered
E

1

7

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");
}
Elba answered 12/3, 2013 at 16:3 Comment(0)
T
14

You need to use the method .LoadFile if you want to load an assembly from a file path:

var assembly = Assembly.LoadFile(parameters.OutputAssembly);
                            ^^^^

According to the documentation, the method .Load:

Loads an assembly given the long form of its name.

It expects an assembly name, like SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3

Thrush answered 12/3, 2013 at 16:13 Comment(1)
+1 - My first thought was it could be an AnyCPU vs x86 vs x64 problem, but having read through msdn, you are right!Disagree

© 2022 - 2024 — McMap. All rights reserved.