C# dynamic compilation of string and .cs file

怎甘沉沦 提交于 2019-12-22 18:37:16

问题


I'm working on a website where a user can implement a C# code solution to a problem in a browser text area and submit it. The server will then compile that code together with a predefined interface I provide on the server. Think of it as a strategy design pattern; I provide a strategy interface and users implement it. So I need to compile a string and a predefined *.cs file together at run-time. Here's the code I have now that compiles only the string portion:

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

CompilerParameters parameters = new CompilerParameters();
parameters.OutputAssembly = "CodeOutputTest.dll";   // need to name this dynamically.  where to store it?
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = false;

CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, request.Code);

Users would submit something like this:

public class UserClass : IStrategy
{
     public string ExecuteSolution(string input)
     {
         // user code
     }
}

Security concerns aside (that's a heavy question for another day)...how can I compile this together with my predefined interface *.cs file? Or is there a better way of handling this?

Thanks!


回答1:


CodeDomProvider.CompileAssemblyFromSource() is defined as

public virtual CompilerResults CompileAssemblyFromSource(
    CompilerParameters options, params string[] sources)

That means you can compile one assembly from multiple source files. Something like:

codeProvider.CompileAssemblyFromSource(parameters, request.Code, otherCode);

Another (possibly better) option is to reference already compiled assembly that contains the code you need. You can do this using CompilerParameters.ReferencedAssemblies:

parameters.ReferencedAssemblies.Add("SomeLibrary.dll");


来源:https://stackoverflow.com/questions/6725817/c-sharp-dynamic-compilation-of-string-and-cs-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!