Project: ShellCommand


Execute shell command and view output result asynchronously.

ShellCommand.png

The ShellProcess class:
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();
							}
						}
					});
	}
}

Last edited Oct 1, 2011 at 11:25 AM by teoarch, version 3

Comments

No comments yet.