Click here to Skip to main content
16,023,339 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello,

I have a weird issue when i try to redirect the input stream of a certain Console application.

My goal is to use a WinForm application to send commands to a Console application and read the output (lets call that application ConsoleApp).

The code below works perfectly for the CMD.exe application but not for my ConsoleApp.

ProcessStartInfo:
C#
procStartInfo.UseShellExecute = false;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.CreateNoWindow = true;
procStartInfo.ErrorDialog = false;

I'm using asyc output reading using events: (that part works perfectly for my ConsoleApp)
C#
proc.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
proc.ErrorDataReceived += new DataReceivedEventHandler(SortOutputHandler);
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();

Input StreamWritter:
StreamWriter sw = proc.StandardInput;
string input = inputTxt.Text + "\r\n";
sw.BaseStream.Write(Encoding.ASCII.GetBytes(input),0,input.Length);
sw.Flush()

The reason I am Encoding the input is because I'll probably use this for Telnet application as well.

The Form: (example with CMD)
Picture


Now for the weird part.
When I do the same in a console application (not a WinForm) and I don't use the StreamWriter shown above, everything I type in the console window goes directly to my ConsoleApp and it works perfectly! All I need to do is redirect the input stream, and nothing more (I don't even use Console.ReadLine() to get what I typed). somehow the application is writing to that stream whatever I type...
The Main functions actually looks like that:
C#
//Config Proc and start it
while (true){
     System.Threading.Thread.Sleep(1000);
}

I know that stupid but it works.

How can I do the same in a WinForm application? or is there another way to redirect input for a console app?
Posted
Updated 19-Oct-10 5:04am
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900