gpt4 book ai didi

c# - 使用 CompileAssemblyFromSource 加载自定义程序集

转载 作者:太空狗 更新时间:2023-10-29 21:09:55 25 4
gpt4 key购买 nike

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

现在这个代理 DLL 中有一个东西,一个接口(interface)。

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 : Could not load file or assembly 'file:///C:\Users...\AppData\Local\Temp\scts5w5o.dll' or one of its dependencies. The system cannot find the file specified.

当然,我的第一个想法是,“...什么是 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;
}

关于c# - 使用 CompileAssemblyFromSource 加载自定义程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10402863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com