Search This Blog

Saturday, October 25, 2008

Execute command from .NET

if you ever want to execute a command ( a simple exe file) and wait for the exit code ,you can find the next c# function very useful.
private static void RunCommand(bool bWaitForExit, string commandName, string arguments, ref string outPut, ref string error)
{
try
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = commandName;
// Redirect the error stream of the child process.
proc.StartInfo.UseShellExecute = false;

proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
// arguments = Server.HtmlDecode(arguments);
arguments = arguments.Trim();
if (arguments.Length != 0) //in case of empty string
proc.StartInfo.Arguments = arguments;
proc.Start();
outPut = proc.StandardOutput.ReadToEnd();
error = proc.StandardError.ReadToEnd();
if (bWaitForExit)
proc.WaitForExit();

}
catch (Exception ex)
{

error = ex.Message;
outPut = error;
}
}

enjoy

No comments: