using System;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace CmdProcess
{
class Program
{
public static void Main(string[] args)
{
InitProcess(@"C:\Windows\System32\cmd.exe", "", null);
p.StandardInput.WriteLine(@"C:Windows\plink.exe root@192.168.2.15");
Console.ReadKey(true);
}
private static Process p = new Process();
private static void InitProcess(string file, string args, string dir)
{
try
{
p.StartInfo.FileName = file;
p.StartInfo.Arguments = args;
if (!string.IsNullOrEmpty(dir))
{
p.StartInfo.WorkingDirectory = dir;
}
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
// // Handle Standard Output
// p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
// p.BeginOutputReadLine();
//
// p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
// p.BeginErrorReadLine();
new Thread(new ThreadStart(GetStdErr)).Start();
new Thread(new ThreadStart(GetStdOut)).Start();
new Thread(new ThreadStart(SetStdIn)).Start();
}
catch (Exception e)
{
Console.Error.WriteLine("SetStdIn: " + e.Message);
//System.Diagnostics.Debug.Print("SetStdIn: " + e.Message);
}
}
private static void CloseProcess()
{
p.Close();
p.Dispose();
}
private static void SetStdIn()
{
string line = "";
try
{
StreamReader reader = new StreamReader(Console.OpenStandardInput());// p.StandardOutput;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
p.StandardInput.WriteLine(line);
}
}
catch (Exception e)
{
Console.Error.WriteLine("SetStdIn: " + e.Message);
//System.Diagnostics.Debug.Print("SetStdIn: " + e.Message);
}
}
private static void GetStdOut()
{
string line = "";
try
{
StreamReader reader = p.StandardOutput;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
Console.WriteLine(line);
//System.Diagnostics.Debug.Print(line);
}
}
catch (Exception e)
{
Console.Error.WriteLine("GetStdOut: " + e.Message);
//System.Diagnostics.Debug.Print("GetStdOut: " + e.Message);
}
}
private static void GetStdErr()
{
string line = "";
try
{
StreamReader reader = p.StandardError;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
Console.WriteLine(line);
//System.Diagnostics.Debug.Print(line);
}
}
catch (Exception e)
{
Console.Error.WriteLine("GetStdErr: " + e.Message);
//System.Diagnostics.Debug.Print("GetStdErr: " + e.Message);
}
}
}
}