c# – 使用CompileAssemblyFromSource加载自定义程序集
发布时间:2020-12-15 08:20:11 所属栏目:百科 来源:网络整理
导读:我不太清楚该怎么做.总体目标是能够获取用户脚本,并在.NET环境中执行它.我已经编写了大部分代码并且工作正常,我不会尝试加载自己的程序集.但是,为了安全地让用户访问系统的内部部分,已经创建了代理DLL.这就是问题所在. 现在这个代理DLL有一个东西,一个接口.
我不太清楚该怎么做.总体目标是能够获取用户脚本,并在.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; 运行上面的代码,它会抛出以下错误:
当然我的第一个想法是,“……什么是scts5w5o.dll?” 这是ScriptProxy.dll无法正确加载,还是ScriptProxy.dll本身试图加载依赖项,这些依赖项位于某个临时文件中?或者它是完全不同的东西? 我应该提一下,我正在从NUnit测试运行器执行此代码.我不确定这是否有所作为. 解决方法
这是因为编译步骤失败,您没有检查错误…
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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |