Tuesday 15 April 2014

Compile and execute C# code at runtime

Add this assemblies

using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;


string source = @"namespace NSTest
                              {
                                public class clstest
                                 {
                                      public string SayMyName(string Name)
                                      {
                                          return Name;
                                      }
                                 }
                              }";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
 {
     {"CompilerVersion", "v3.5"}
 };
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

CompilerParameters compilerParams = new CompilerParameters
{
    GenerateInMemory = true,
    GenerateExecutable = false
};

/// add assembly runtime
compilerParams.ReferencedAssemblies.Add("System.Drawing.dll");

// Compile code
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);

// Check if code has any error ??                       
if (results.Errors.HasErrors)
 {
      StringBuilder error = new StringBuilder();
      foreach (CompilerError item in results.Errors)
      {
          error.AppendLine(item.ErrorText);
       }
       throw new Exception(error.ToString());
 }

// create instance of class using Reflection
object objClass = results.CompiledAssembly.CreateInstance("NSTest.clstest");
// Find method
MethodInfo objMI = objClass.GetType().GetMethod("SayMyName");
// Invoke method

string str = objMI.Invoke(objClass, new object[] { "Ajay" }).ToString();




No comments:

Post a Comment