An Interactive Console I/O Wrapper/Interceptor in C# - What is the issue?

Posted by amazedsaint on Stack Overflow See other posts from Stack Overflow or by amazedsaint
Published on 2010-05-24T16:08:19Z Indexed on 2010/05/24 16:11 UTC
Read the original article Hit count: 301

Filed under:
|
|
|

I was trying to put together an interactive Console interceptor/wrapper in C# over the weekend, by re-mixing few code samples I've found in SO and other sites. With what I've as of now, I'm unable to read back from the console reliably. Any quick pointers?

public class ConsoleInterceptor
    {
        Process _interProc;

        public event Action<string> OutputReceivedEvent;

        public ConsoleInterceptor()
        {
            _interProc = new Process();
            _interProc.StartInfo = new ProcessStartInfo("cmd");
            InitializeInterpreter();
        }

        public ConsoleInterceptor(string command)
        {
            _interProc = new Process();
            _interProc.StartInfo = new ProcessStartInfo(command);
            InitializeInterpreter();
        }

        public Process InterProc
        {
            get
            {
                return _interProc;
            }
        }

        private void InitializeInterpreter()
        {
            InterProc.StartInfo.RedirectStandardInput = true;
            InterProc.StartInfo.RedirectStandardOutput = true;
            InterProc.StartInfo.RedirectStandardError = true;
            InterProc.StartInfo.CreateNoWindow = true;
            InterProc.StartInfo.UseShellExecute = false;
            InterProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            bool started = InterProc.Start();

            Redirect(InterProc.StandardOutput);
            Redirect(InterProc.StandardError);

        }

        private void Redirect(StreamReader input)
        {
            new Thread((a) =>
            {
                var buffer = new char[1];
                while (true)
                {
                    if (input.Read(buffer, 0, 1) > 0)
                        OutputReceived(new string(buffer));
                };
            }).Start();
        }

        private void OutputReceived(string text)
        {
            if (OutputReceivedEvent != null)
                OutputReceivedEvent(text);
        }


        public void Input(string input)
        {
            InterProc.StandardInput.WriteLine(input);
            InterProc.StandardInput.Flush();
        }

    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about process