title: How to use an interactive command line program from another .NET program
body: <p>I need to write a wrapper for an interactive command line program.</p>
  
  <p>That means I need to be able to send commands to the other program via its standard input und receive the response via its standard output.</p>
  
  <p>The problem is, that the standard output stream seems to be blocked while the input stream is still open. As soon as I close the input stream I get the response. But then I cannot send more commands.</p>
  
  <p>This is what I am using at the moment (mostly from <a href="https://stackoverflow.com/a/3308697/680151">here</a>):</p>
  
  <pre><code>void Main() {
      Process process;
      process = new Process();
      process.StartInfo.FileName = "atprogram.exe";
      process.StartInfo.Arguments = "interactive";
  
      // Set UseShellExecute to false for redirection.
      process.StartInfo.UseShellExecute = false;
      process.StartInfo.CreateNoWindow = true;
  
      // Redirect the standard output of the command.  
      // This stream is read asynchronously using an event handler.
      process.StartInfo.RedirectStandardOutput = true;
      // Set our event handler to asynchronously read the output.
      process.OutputDataReceived += (s, e) =&gt; Console.WriteLine(e.Data);
  
      // Redirect standard input as well. This stream is used synchronously.
      process.StartInfo.RedirectStandardInput = true;
      process.Start();
  
      // Start the asynchronous read of the output stream.
      process.BeginOutputReadLine();
  
      String inputText;
      do 
      {
          inputText = Console.ReadLine();
          if (inputText == "q")
          {
              process.StandardInput.Close();   // After this line the output stream unblocks
              Console.ReadLine();
              return;
          }
          else if (!String.IsNullOrEmpty(inputText))
          {
              process.StandardInput.WriteLine(inputText);
          }
      }
  }
  </code></pre>
  
  <p>I also tried reading the standard output stream synchronously, but with the same result. Any method call on the output stream block indefinitely until the input stream is closed - even <code>Peek()</code> and <code>EndOfStream</code>.</p>
  
  <p>Is there any way to communicate with the other process in a full duplex kind of way?</p>