Last active
June 7, 2017 04:51
-
-
Save zrrtcs/7156d31e031c79fe9c54b100cf3ddd02 to your computer and use it in GitHub Desktop.
Execute command on cmd from 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
| //modified from https://stackoverflow.com/a/15878837/273743 | |
| string ExecuteCommandSync(object command) | |
| { | |
| try | |
| { | |
| // create the ProcessStartInfo using "cmd" as the program to be run, | |
| // and "/c " as the parameters. | |
| // Incidentally, /c tells cmd that we want it to execute the command that follows, | |
| // and then exit. | |
| System.Diagnostics.ProcessStartInfo procStartInfo = | |
| new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); | |
| // The following commands are needed to redirect the standard output. | |
| // This means that it will be redirected to the Process.StandardOutput StreamReader. | |
| procStartInfo.RedirectStandardOutput = true; | |
| procStartInfo.UseShellExecute = false; | |
| // Do not create the black window. | |
| procStartInfo.CreateNoWindow = true; | |
| // Now we create a process, assign its ProcessStartInfo and start it | |
| System.Diagnostics.Process proc = new System.Diagnostics.Process(); | |
| proc.StartInfo = procStartInfo; | |
| proc.Start(); | |
| // Get the output into a string | |
| string result = proc.StandardOutput.ReadToEnd(); | |
| // Display the command output. | |
| return (result); | |
| } | |
| catch (Exception objException) | |
| { | |
| // Log the exception | |
| return objException.Message; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment