4

Possible Duplicate:
Execute a string in C# 4.0

How can I get this string to execute:

string dt = "DateTime.Now";

...so that this would result in today's date being displayed?:

lbl.Text = dt;
0

1 Answer 1

8

Solution with Codedom:

private static string CreateExecuteMethodTemplate(string content)
{
    var builder = new StringBuilder();

    builder.Append("using System;");
    builder.Append("\r\nnamespace Lab");
    builder.Append("\r\n{");
    builder.Append("\r\npublic sealed class Cal");
    builder.Append("\r\n{");
    builder.Append("\r\npublic static object Execute()");
    builder.Append("\r\n{");
    builder.AppendFormat("\r\nreturn {0};", content);
    builder.Append("\r\n}");
    builder.Append("\r\n}");
    builder.Append("\r\n}");

    return builder.ToString();
}

private static object Execute(string content)
{
    var codeProvider = new CSharpCodeProvider();
    var compilerParameters = new CompilerParameters
    {
        GenerateExecutable = false,
        GenerateInMemory = true
    };

    compilerParameters.ReferencedAssemblies.Add("system.dll");

    string sourceCode = CreateExecuteMethodTemplate(content);
    CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode);
    Assembly assembly = compilerResults.CompiledAssembly;
    Type type = assembly.GetType("Lab.Cal");
    MethodInfo methodInfo = type.GetMethod("Execute");

    return methodInfo.Invoke(null, null);
}

So you can call:

var result = Execute("DateTime.Now");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.