0

I want to compile a C# console application inside my application and get the returned result somehow. I want this to happen silently(i don't want the console to actually show etc.) Lets say i have this code

private Assembly BuildAssembly(string code)
{
    Microsoft.CSharp.CSharpCodeProvider provider = 
       new CSharpCodeProvider();
    ICodeCompiler compiler = provider.CreateCompiler();
    CompilerParameters compilerparams = new CompilerParameters();
    compilerparams.GenerateExecutable = false;
    compilerparams.GenerateInMemory = true;
    CompilerResults results = 
       compiler.CompileAssemblyFromSource(compilerparams, code);
    if (results.Errors.HasErrors)
    {
        StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
        foreach (CompilerError error in results.Errors )
        {
            errors.AppendFormat("Line {0},{1}\t: {2}\n", 
                   error.Line, error.Column, error.ErrorText);
        }
        throw new Exception(errors.ToString());
    }
    else
    {
        return results.CompiledAssembly;
    }
}

How would i execute the assembly and get the results?

Georgi-it
  • 3,676
  • 1
  • 20
  • 23
  • I'd probably create it on a separate Thread if you want it to happen silently – Stokedout Jun 23 '13 at 19:56
  • The separate thread part is not hard, i am aware of the fact that it's gonna be multithreaded. I just need general method of execution and getting the value – Georgi-it Jun 23 '13 at 20:12
  • 1
    It looks like you copied your code from [the article Code0987 linked](http://www.codeproject.com/Articles/9019/Compiling-and-Executing-Code-at-Runtime). Why did you use just one part of the article and are asking about something that's explained in the rest of the article? – svick Jun 23 '13 at 20:58

1 Answers1

3

Here's something I found -

public object ExecuteCode(string code, string namespacename, string classname, string functionname, bool isstatic, params object[] args)
{
    var asm = BuildAssembly(code);
    object instance = null;
    Type type;
    if(isstatic)
    {
        type = asm.GetType(namespacename + "." + classname);
    }
    else
    {
        instance = asm.CreateInstance(namespacename + "." + classname);
        type = instance.GetType();
    }
    return type.GetMethod(functionname).Invoke(instance, args);
}

This method simply extends your BuildAssembly function.

Source

Code0987
  • 2,598
  • 3
  • 33
  • 51