I’ve got a web application that has a page full of batch files which the user can run, view the output, and send input. My problem occurs when the process hits something which causes it to pause, such as a pause, or a question that requires the user to press Y or N to continue. We’ll go with pause for the purposes of this question.
This is my batch file:
pause
When run in windows, I get the output displayed on my screen “Press any key to continue…”, I press enter, and it exits. But when my app runs this batch file, I dont get any output, but I know what it’s waiting for so I press enter, and only then do I see the output “Press any key to continue…”.
I’ve created a simplified version of my code in a console app, and the same thing happens, I get a blank screen, I press enter, and then I see “Press any key to continue…”
Any idea how I go about getting this line of output BEFORE I am required to press the key?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace BatchCaller
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = @"C:\Projects\BatchCaller\BatchCaller\Test2.bat",
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
Process proc = new Process();
proc.StartInfo = psi;
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.BeginOutputReadLine();
// Problem is not here, ignore this, just my temporary input method.
// Problem still occurs when these two lines are removed.
string inputText = Console.ReadLine();
proc.StandardInput.WriteLine(inputText);
proc.WaitForExit();
}
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
// This method doesnt get called for output: "Press any key to continue..."
// Why?
if (e.Data != null)
Console.WriteLine(e.Data);
}
}
}
I realised it wasn’t reading the last line because the
data receivedevent was only being triggered after there was a whole line of output, but when it pauses or asks a question, the cursor is still on the same line. A new thread that continuously checked the output stream was the solution to this small problem.I also managed to solve my whole problem so that now what I’ve got when I run a script close ly resembles a command prompt window.
Here’s a very basic summary of how it works:
I start a new process that runs a batch file. At the same time I start a new thread that continuously loops asking the process for more output, and storing that output in a queue. My .NET timer continuously checks the queue for text, and outputs it into my ajax panel. I use a text box and ajax to input text into the process input and into my ajax panel. I also needed a lot of javascript and I had to use session variables to make it run smoothly.