1

にいくつかのキーワードが表示されたら、プログラムを終了したいと思いますConsole.Out。これは、特定の例外が発生したときに終了しないという問題があるサードパーティの DLL を使用しているためです。

私たちにとって唯一の解決策は、に戻されるログを監視しているようconsole.Outです。また、ログオンに基づいてconsole.out、ホスト アプリケーションは、そのような例外が発生したときに何をすべきかを決定できます。

トレースリスナーを使用できると誰かが私に言いました...しかし、それについてはわかりません。皆さんはどう思いますか?

4

2 に答える 2

4

このConsoleクラスは、SetOut出力をカスタム ストリームに書き込むために使用できるメソッドを提供します。たとえば、StringBuilder にストリーミングして変更を監視したり、キーワードを監視するカスタム ストリーム実装を作成したりできます。

たとえば、KeywordWatcherStreamWrapper指定されたキーワードを監視し、キーワードが検出されるたびにすべてのリスナーに対してイベントを発生させるクラスを次に示します。

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);
    }
}

使用例:

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); }

キーワード全体を含む2 番目のWriteステートメントでイベントが発生し、例外がスローされます。また、これにより基になるストリームが暗黙的にラップされ、引き続きそれに書き込まれるため、コンソール出力は引き続き通常どおり生成されることに注意してください。

出力例:

Testing
Hel
lo
Hello
Keyword found!
于 2012-05-14T22:26:15.477 に答える
0

これをexeにラップできる場合は、Process.StandardOutputを使用できます。

于 2012-05-14T22:26:26.333 に答える