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

6

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");
}
c#
unit-testing
nunit
csharpcodeprovider
assembly.load
asked on Stack Overflow Mar 12, 2013 by ChaseMedallion • edited Mar 13, 2013 by abatishchev

1 Answer

10

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

answered on Stack Overflow Mar 12, 2013 by mellamokb

User contributions licensed under CC BY-SA 3.0