Here, we are compiling the c# code at runtime, and executing the result directly from in memory. The class is instantiated, and the method is called dynamically. The result, in this case a string is read back after the code executes
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
public string RunCodeSnippet(string sCSharpCodeSnippet)
{
string sCSharpSource =
@"using System;
namespace com.mycomp
{
public class MyClass
{
public string RunCSharpScript()
{
return(" + sCSharpCodeSnippet + @");
}
}
}";
Dictionary<string, string> csProviderOptions = new Dictionary<string, string> { { "CompilerVersion", "v3.5" } };
CSharpCodeProvider csProvider = new CSharpCodeProvider(csProviderOptions);
CompilerParameters csCompilerParams = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false };
CompilerResults csCompresults = csProvider.CompileAssemblyFromSource(csCompilerParams, sCSharpSource);
if (csCompresults.Errors.HasErrors)
{
throw new Exception("Compile Error! - " + csCompresults.Errors[0] + Environment.NewLine + sCSharpSource);
}
object o = csCompresults.CompiledAssembly.CreateInstance("com.mycomp.MyClass");
MethodInfo mi = o.GetType().GetMethod("RunCSharpScript");
var dataout = mi.Invoke(o, null);
return (string)dataout;
}
Sample Usage:
try
{
string sResult = RunCodeSnippet("\"The time now is : \" + DateTime.Now.ToString()");
}
catch (Exception ex)
{
sError = ex.Message;
}