Executing Command Line Strings Programatically
//*************************************************
//*************************************************
//********** EXECUTE COMMAND LINE STRING **********
//*************************************************
//*************************************************
private string ExecuteCommandLineString(string CommandString)
{
try
{
System.Diagnostics.Process Process1 = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo StartInfo1 = new System.Diagnostics.ProcessStartInfo();
StartInfo1.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
StartInfo1.FileName = "cmd.exe";
StartInfo1.Arguments = "/C " + CommandString;
StartInfo1.RedirectStandardOutput = true;
StartInfo1.UseShellExecute = false;
Process1.StartInfo = StartInfo1;
Process1.Start();
//Do not wait for the child process to exit before reading to the end of its redirected stream.
//p.WaitForExit();
//Read the output stream first and then wait.
string Output = Process1.StandardOutput.ReadToEnd();
Process1.WaitForExit();
return (Output);
}
catch (Exception ex)
{
return("ERROR - " + ex.Message + "\n");
}
}
Example usage copying a file
string Command = "xcopy \"C:\\My Folder\\HelloWorld.txt\" \"C:\\My Folder\\HelloWorld2.txt\" /-I /Y ";
string Output = ExecuteCommandLineString(Command);
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.