In given below code ExecuteCode() is a method which is use for run time compilation. codeToCompile is a complete method which you have to execute and userid and password are the passing parameters of method body codeToCompile .
using System.CodeDom.Compiler;
using System.Reflection;
namespace CodeExecution
{
public class CodeExecution
{
public static string ExecuteCode(string codeToCompile, string userid, string password)
{
CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider();
ICodeCompiler iCodeCompiler = cSharpCodeProvider.CreateCompiler();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.ReferencedAssemblies.Add("system.dll");
compilerParameters.CompilerOptions = "/t:library";
compilerParameters.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CodeExecution{ \n");
sb.Append("public class CodeExecution{ \n");
sb.Append(codeToCompile + "\n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults compilerResults = iCodeCompiler.CompileAssemblyFromSource(compilerParameters, sb.ToString());
if (compilerResults.Errors.Count > 0)
{
return null;
}
System.Reflection.Assembly a = compilerResults.CompiledAssembly;
object o = a.CreateInstance("CodeExecution.CodeExecution"); //get namespace name and then class name- you can change according to your code
Type t = o.GetType();
MethodInfo mi = t.GetMethod("StringParser"); //StringParser is the name of method-you can change according to your code
object[] oParams = new object[] { userid, password }; //parameters of method
object s = mi.Invoke(o, oParams);
string result = (string)s;
return result;
}
}
}
Referred Link : http://www.codeproject.com/Articles/11939/Evaluate-C-Code-Eval-Function
Hope this code will help you.Thanks
0 Comment(s)