6

我不太确定该去哪里。总体目标是能够获取用户脚本,并在 .NET 环境中执行它。如果我不尝试加载自己的程序集,我已经编写了大部分代码并且一切正常。但是,为了让用户安全地访问系统的内部部分,我们创建了一个代理 DLL。这似乎是问题所在。

现在这个代理 DLL 里面有一个东西,一个接口。

CompilerParameters options = new CompilerParameters();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("ScriptProxy.dll");

Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
CompilerResults result = provider.CompileAssemblyFromSource(options, script);

// This line here throws the error:
return result.CompiledAssembly;

运行上面的代码,它会抛出以下错误:

System.IO.FileNotFoundException:无法加载文件或程序集 'file:///C:\Users...\AppData\Local\Temp\scts5w5o.dll' 或其依赖项之一。该系统找不到指定的文件。

当然,我的第一个想法是,“……什么是 scts5w5o.dll?”

这是ScriptProxy.dll没有正确加载,还是 ScriptProxy.dll 本身试图加载依赖项,这些依赖项位于某个临时文件中?还是完全不同的东西?

我应该提一下,我正在从 NUnit 测试运行程序执行此代码。我不确定这是否会有所不同。

4

2 回答 2

8

这是因为编译步骤失败并且您没有检查它是否有错误...

    static Assembly Compile(string script)
    {
        CompilerParameters options = new CompilerParameters();
        options.GenerateExecutable = false;
        options.GenerateInMemory = true;
        options.ReferencedAssemblies.Add("System.dll");
        options.ReferencedAssemblies.Add("ScriptProxy.dll");

        Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
        CompilerResults result = provider.CompileAssemblyFromSource(options, script);

        // Check the compiler results for errors
        StringWriter sw = new StringWriter();
        foreach (CompilerError ce in result.Errors)
        {
            if (ce.IsWarning) continue;
            sw.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText);
        }
        // If there were errors, raise an exception...
        string errorText = sw.ToString();
        if (errorText.Length > 0)
            throw new ApplicationException(errorText);

        return result.CompiledAssembly;
    }
于 2012-05-01T19:24:33.530 回答
4

我不认为标记为的帖子answer真的是一个答案...但是我在这里找到了答案

parameters.ReferencedAssemblies.Add(typeof(<TYPE FROM DOMAIN.DLL>).Assembly.Location);

这意味着如果您尝试添加dll第三方引用(有时 .net dll 也会给出例外),那么只需将其复制到executable folder.. 它会正常工作.. 否则您也可以在那里定义完整路径..

于 2015-10-29T08:42:27.897 回答