Madhanmohan S said:
I have application which will run in commandline mode. When i start
the application, it will go to a specific mode (Similar like, when we use
OSql for MSDE). In this mode, we have to give different commands to execute
our tasks. I tried with StandardInput Method. But i was not able to execute
the commands, in the application mode.
When i use the StandardInputMethod to pass the commands, the C#
application hangs.
Are you reading from StandardOutput and StandardError? Perhaps the
other process is blocking.
Can you point some resources or sample code for the same???
Sure. First, a very simple echo program:
using System;
public class Echo
{
static void Main()
{
string line;
while ((line=Console.ReadLine())!="quit")
Console.WriteLine ("Echo: {0}", line);
}
}
Compile it (to echo.exe, as a command-line app) and run it - basically
it echoes what you type until you type "quit".
Now here's something to automate it:
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
public class AutoEcho
{
static void Main()
{
ProcessStartInfo psi = new ProcessStartInfo("echo.exe");
psi.RedirectStandardOutput=true;
psi.RedirectStandardInput=true;
psi.UseShellExecute=false;
psi.CreateNoWindow=true;
Process proc = Process.Start (psi);
// Start a new thread to read from its standard output
ProcessOutputReader por = new ProcessOutputReader (proc);
por.Start();
proc.StandardInput.WriteLine ("Hello");
proc.StandardInput.WriteLine ("There");
proc.StandardInput.WriteLine ("quit");
}
class ProcessOutputReader
{
Process proc;
public ProcessOutputReader (Process proc)
{
this.proc = proc;
}
public void Start()
{
new Thread (new ThreadStart(ReadAll)).Start();
}
void ReadAll()
{
StreamReader reader = proc.StandardOutput;
string line;
while ((line = reader.ReadLine())!=null)
Console.WriteLine ("Process output: {0}", line);
}
}
}