Skip to content

Instantly share code, notes, and snippets.

@duncansmart
Created September 26, 2012 13:22
Show Gist options
  • Save duncansmart/3787999 to your computer and use it in GitHub Desktop.
Save duncansmart/3787999 to your computer and use it in GitHub Desktop.
Command/console exec in C#
class ConsoleExec
{
public string FileName { get; set; }
public string Arguments { get; set; }
public TextWriter StdOut { get; set; }
public TextWriter StdErr { get; set; }
public ConsoleExec()
{
StdOut = new StringWriter();
StdErr = new StringWriter();
}
public ConsoleExec(string fileName, string arguments)
: this()
{
FileName = fileName;
Arguments = arguments;
}
public int Execute()
{
using (var process = new Process())
{
var psi = process.StartInfo;
psi.RedirectStandardError = psi.RedirectStandardInput = psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.FileName = FileName;
psi.Arguments = Arguments;
if (StdOut != null)
{
process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
StdOut.WriteLine(e.Data);
};
}
if (StdErr != null)
{
process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
StdErr.WriteLine(e.Data);
};
}
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return process.ExitCode;
}
}
static void execTest()
{
string filename = "cmd.exe";
string args = "/c dir /s";
var exec = new ConsoleExec(filename, args);
int exitCode = exec.Execute();
Debug.WriteLine("exit code - " + exitCode);
Debug.WriteLine("stdOut - " + exec.StdOut);
Debug.WriteLine("stdErr - " + exec.StdErr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment