Execute shell command and view output result asynchronously.
public class ShellProcess
{
public void Execute(Action<string> action, Action endAction = null, params ShellCommand[] commands)
{
new AsyncWorker()
.RunWorkerAsync(
commands,
p =>
{
using (var cmdProcess = new Process())
{
var startInfo =
new ProcessStartInfo
{
FileName = Environment.GetEnvironmentVariable("COMSPEC"),
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
};
cmdProcess.StartInfo = startInfo;
cmdProcess.Start();
using (var writer = cmdProcess.StandardInput)
{
writer.AutoFlush = true;
foreach (var command in commands)
{
writer.WriteLine(string.Format("{0} {1}", command.Name, command.Parameter));
}
writer.Close();
}
while (!cmdProcess.StandardOutput.EndOfStream)
{
action(cmdProcess.StandardOutput.ReadLine());
}
if (endAction != null)
{
endAction();
}
}
});
}
}