加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

奇怪的Assembly.Load错误尝试加载使用C#代码提供程序编译的程序

发布时间:2020-12-15 04:25:35 所属栏目:百科 来源:网络整理
导读:我正在尝试使用C#代码提供程序从我的代码编译程序集. 当我使用compilerResult.CompiledAssembly访问已编译的程序集时,一切正常.但是,当我改为执行Assembly.Load(路径)时,我得到以下异常: System.IO.FileLoadException : Could not load file or assembly ‘
我正在尝试使用C#代码提供程序从我的代码编译程序集.

当我使用compilerResult.CompiledAssembly访问已编译的程序集时,一切正常.但是,当我改为执行Assembly.Load(路径)时,我得到以下异常:

System.IO.FileLoadException : Could not load file or assembly
‘C:UsersNameDesktopoutput.dll’ or one of its dependencies. The
given assembly name or codebase was invalid. (Exception from 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");
}

解决方法

如果要从文件路径加载程序集,则需要使用方法 .LoadFile
var assembly = Assembly.LoadFile(parameters.OutputAssembly);
                            ^^^^

根据文档,方法.Load

Loads an assembly given the long form of its name.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读