This example shows the technique called as process piping. Process piping is a technique to redirect input/out form a process to get the result in runtime. This enable us to execute any process with a given set of parameters and capture the output. In the example below weare invoking the command shell(cmd.exe) to do a ping on "Bing.com" and capture the output in the console.
We can further create a function which does the same for us, and alter the behaviour by sending different parameters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
ProcessStartInfo cmdStartInfo = new ProcessStartInfo(); | |
cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe"; | |
cmdStartInfo.RedirectStandardOutput = true; | |
cmdStartInfo.RedirectStandardError = true; | |
cmdStartInfo.RedirectStandardInput = true; | |
cmdStartInfo.UseShellExecute = false; | |
cmdStartInfo.CreateNoWindow = true; | |
Process cmdProcess = new Process(); | |
cmdProcess.StartInfo = cmdStartInfo; | |
cmdProcess.ErrorDataReceived += cmd_Error; | |
cmdProcess.OutputDataReceived += cmd_DataReceived; | |
cmdProcess.EnableRaisingEvents = true; | |
cmdProcess.Start(); | |
cmdProcess.BeginOutputReadLine(); | |
cmdProcess.BeginErrorReadLine(); | |
cmdProcess.StandardInput.WriteLine("dir"); //Execute ping bing.com | |
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit. | |
cmdProcess.WaitForExit(); | |
} | |
static void cmd_DataReceived(object sender, DataReceivedEventArgs e) | |
{ | |
Console.WriteLine(e.Data); | |
} | |
static void cmd_Error(object sender, DataReceivedEventArgs e) | |
{ | |
Console.WriteLine("Error from other process"); | |
Console.WriteLine(e.Data); | |
} | |
We can further create a function which does the same for us, and alter the behaviour by sending different parameters.