I want to get the stdout of a dynamically compiled code.
My code:
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var source = File.ReadAllText("form.cs");
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v4.0"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
ReferencedAssemblies = {"System.dll" ,"mscorlib.dll"}
};
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
Assembly assembly = results.CompiledAssembly;
Type program = assembly.GetType("program.TestPerson");
MethodInfo main = program.GetMethod("Main");
var outp= main.Invoke(null, null);
//Console.WriteLine(outp);
Console.ReadLine();
}
}
}
The content of form.cs:
using System;
namespace program {
public class TestPerson
{
public static void Main()
{
var person1 = new Person();
Console.WriteLine(person1.Name);
}
}
}
public class Person
{
public Person()
{
Name = "unknown";
}
public Person(string name)
{
Name = name;
}
public string Name { get;set; }
public override string ToString()
{
return Name;
}
}
What I exactly want is to have the stdout of form.cs (Console.WriteLine) after compilation in a variable in parent applicaton, by the way, I do NOT want to build the code into the file and run it as process and read its output. Also assume the content of form.cs is NOT editable.