Question

I want to exit the program if I see some key words apprearing in Console.Out. This is because we use a third party DLL which has a problem that when it encounters some particular exception it never exits.

The only sulotion to us seems to be monitoring the log that is populated back to console.Out. And base on the log on console.out, the host application can edecide what to do when such exception are encountered.

Someone told me that I can use trace listener... but I am not sure about that. what do you guys think?

Was it helpful?

Solution

The Console class provides the SetOut method which can be used to write output to a custom stream. For example, you could stream to a StringBuilder and monitor changes, or write a custom stream implementation that watches for the keywords.

For example, here is a KeywordWatcherStreamWrapper class that watches for specified keyword, and raises an event for all listeners whenever the keyword is seen:

public class KeywordWatcherStreamWrapper : TextWriter
{
    private TextWriter underlyingStream;
    private string keyword;
    public event EventHandler KeywordFound;
    public KeywordWatcherStreamWrapper(TextWriter underlyingStream, string keyword)
    {
        this.underlyingStream = underlyingStream;
        this.keyword = keyword;
    }

    public override Encoding Encoding
    {
        get { return this.underlyingStream.Encoding; }
    }

    public override void Write(string s)
    {
        this.underlyingStream.Write(s);
        if (s.Contains(keyword))
            if (KeywordFound != null)
                KeywordFound(this, EventArgs.Empty);
    }

    public override void WriteLine(string s)
    {
        this.underlyingStream.WriteLine(s);
        if (s.Contains(keyword))
            if (KeywordFound != null)
                KeywordFound(this, EventArgs.Empty);
    }
}

Sample usage:

var kw = new KeywordWatcherStreamWrapper(Console.Out, "Hello");
kw.KeywordFound += (s, e) => { throw new Exception("Keyword found!"); };

try {   
    Console.SetOut(kw);
    Console.WriteLine("Testing");
    Console.WriteLine("Hel");
    Console.WriteLine("lo");
    Console.WriteLine("Hello");
    Console.WriteLine("Final");
} catch (Exception ex) { Console.Write(ex.Message); }

On the second Write statement which contains the entire keyword, the event will be raised and thus the exception will be thrown. Note also that this silently wraps the underlying stream and still writes to it, so console output is still generated as normal.

Sample output:

Testing
Hel
lo
Hello
Keyword found!

OTHER TIPS

if you can wrap this into an exe, maybe you can use Process.StandardOutput.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top