C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,853 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
static void Main(string[] args)
{
EventWaitHandle _mainProcessEventWait = new EventWaitHandle(false, EventResetMode.ManualReset);
bool _run = true;
var psi = new ProcessStartInfo()
{
FileName = "cmd.exe",
CreateNoWindow = true,
WorkingDirectory = AppContext.BaseDirectory,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
Process process = Process.Start(psi);
var sinput = Task.Factory.StartNew(() =>
{
using (StreamWriter sw = process.StandardInput)
{
while (_run)
{
var _command = Console.ReadLine();
sw.WriteLine(_command);
if (_command == "exit" || _command == "exit;")
{
_run = false;
_mainProcessEventWait.Set();
}
}
}
});
var sout = Task.Factory.StartNew(() =>
{
using (StreamReader sr = process.StandardOutput)
{
char[] buffer = new char[1];
while (sr.BaseStream.CanRead)
{
if(!sr.EndOfStream) //when reading to end. this code will clog current thread?
sr.Read(buffer, 0, 1);//clog current thread
sr.ReadLine();//clog current thread
Console.Write(buffer);
}
}
});
_mainProcessEventWait.WaitOne();
Console.WriteLine("end");
}
If you want to intercept and display the output, then try this:
var sout = Task.Factory.StartNew( ( ) =>
{
process.StandardOutput.BaseStream.CopyTo( Console.OpenStandardOutput( ) );
} );
var serr = Task.Factory.StartNew( ( ) =>
{
process.StandardError.BaseStream.CopyTo( Console.OpenStandardOutput( ) );
} );
Note that CanRead indicates that the stream supports reading; it does not mean that the data are available.