Created
September 26, 2012 13:22
-
-
Save duncansmart/3787999 to your computer and use it in GitHub Desktop.
Command/console exec in C#
This file contains hidden or 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
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