Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mono Evaluator class

Tags:

c#

.net

mono

I'm using the Mono Evaluator class to run C# scripts. If there is a syntax error in the code, the error gets output to the Console. I would rather have the output returned to a String. I know I can redirect the entire console, but I would prefer to just get the output of the Evaluator.

There is a MessageOutput property which is a TextWriter, but I have no idea what to do with it.

like image 986
FlappySocks Avatar asked Jan 25 '26 09:01

FlappySocks


2 Answers

Just going to guess here...

Create a new System.IO.StringWriter and assign it to MessageOutput?

If it works, you can get the contents of the StringWriter via ToString().

like image 85
codekaizen Avatar answered Jan 27 '26 21:01

codekaizen


I know this is an old question, but I was just looking for an answer too. Here's what I ended up doing to capture the output (which may or may not be "Error" output, you would need to parse it) in the var lastOutput.

The idea is this:

1) Create a new ConsoleReportPrinter and pass in the CustomTextWriter so we can capture the Write/WriteLine calls
2) Then pass that new ReportPrinter to the Evaluator as part of a new CompilerContext

class CustomTextWriter : TextWriter
{
    private string lastOutput { get; set; }
    public CustomTextWriter() { }
    public override void Write(string value)
    {
        lastOutput = value;
        Console.Write(value);
    }
    public override void WriteLine(string value)
    {
        lastOutput = value;
        Console.WriteLine(value);
    }
    public override Encoding Encoding
    {
        get
        {
            return Encoding.Default;
        }
    }
}
static void Main(string[] args)
{
    ReportPrinter r = new ConsoleReportPrinter(new CustomTextWriter());
    evaluator = new Evaluator(new CompilerContext(
                        new CompilerSettings(),
                        r));
    // all evaluations now will pass through our CustomTextWriter
}
like image 22
sorrell Avatar answered Jan 27 '26 22:01

sorrell