【问题标题】:Weird Assembly.Load error trying to load assembly compiled with C# code provider尝试加载使用 C# 代码提供程序编译的程序集时出现奇怪的 Assembly.Load 错误
【发布时间】:2013-03-12 16:03:13
【问题描述】:

我正在尝试使用 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");
}

【问题讨论】:

    标签: c# unit-testing nunit csharpcodeprovider assembly.load


    【解决方案1】:

    如果要从文件路径加载程序集,则需要使用方法.LoadFile

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

    根据文档,方法.Load

    加载一个给定长格式名称的程序集。

    它需要一个程序集名称,例如 SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3

    【讨论】:

    • +1 - 我的第一个想法是这可能是 AnyCPU vs x86 vs x64 问题,但是通过 msdn 阅读,你是对的!
    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2014-12-08
    • 1970-01-01
    相关资源
    最近更新 更多