Thursday, January 22, 2009

C# - How to run a program in DOS command

The approach that comes in the following, could similarly be used to run command line tools, and DOS commands.

public bool runAcmd(string strCmd, string strCmdWorkDir)
{
// "strCmd" can contain command line arguments
bool returnVal = true;
Process prcs;
ProcessStartInfo psi = new ProcessStartInfo();

psi.FileName = "cmd";
psi.Arguments = " /c " + strCmd;
psi.WorkingDirectory = strCmdWorkDir;
psi.WindowStyle = ProcessWindowStyle.Hidden;

try
{
   prcs = Process.Start(psi);
   // wait value is in milliseconds
   if (!prcs.WaitForExit(10000))
      returnVal = false;
}
catch (Exception ex)
{
   returnVal = false;
}
finally
{
   // Some lines of code to execute in
   // case of error or not, if necessary
}
return returnVal;
}

Share/Bookmark

No comments: