First, how to make DOS command silently execute, do not pop up console window?
1. The "cmd.exe" command with "/C" parameter is required to exit the console immediately after executing the command.
2. Set Startinfo.useshellexecute = false; To start a process without using the system shell
3. Set Startinfo.createnowindow = true; Do not create a window
Second, how to get the result of DOS command execution?
1. Set startinfo.redirectstandardoutput = true; REDIRECT output instead of default display in DOS console
2. Use process. StandardOutput to read the results.
Third, the source program
I've encapsulated this sequence of operations into the method execute for class Doscommandoutput, see below:
Using System;
Using System.Text;
Using System.Diagnostics;
Namespace Wuya.getdoscommandoutput
{
<summary>
DOS command Output class
</summary>
Class Doscommandoutput
{
<summary>
Executes a DOS command that returns the output of a DOS command
</summary>
<param name= "doscommand" >dos command </param>
<returns> returns the output, if an exception occurs, returns an empty string </returns>
public static string Execute (String doscommand)
{
Return Execute (Doscommand, 60 * 1000);
}
<summary>
Executes a DOS command that returns the output of a DOS command
</summary>
<param name= "doscommand" >dos command </param>
<param name= "milliseconds" > Wait Time for command execution (in milliseconds), if set to 0, infinite wait </param>
<returns> returns the output, if an exception occurs, returns an empty string </returns>
public static string Execute (string doscommand, int milliseconds)
{
String output = ""; Output string
if (Doscommand! = NULL && Doscommand! = "")
{
Process process = new process (); Create a Process Object
ProcessStartInfo startinfo = new ProcessStartInfo ();
Startinfo.filename = "cmd.exe"; Set the command to be executed
Startinfo.arguments = "/C" + Doscommand; Set the parameter, where "/C" means to exit immediately after executing the command
Startinfo.useshellexecute = false; Booting without using the system shell
Startinfo.redirectstandardinput = false; Do not redirect input
Startinfo.redirectstandardoutput = true; REDIRECT Output
Startinfo.createnowindow = true; Do not create a window
Process. StartInfo = StartInfo;
Try
{
if (process. Start ())//BEGIN Process
{
if (milliseconds = = 0)
Process. WaitForExit (); Here the infinite waits for the process to end
Else
Process. WaitForExit (milliseconds); Here waits for the process to end, waiting time for the specified millisecond
Output = process. Standardoutput.readtoend ();//output of the Read process
}
}
Catch
{
}
Finally
{
if (process! = NULL)
Process. Close ();
}
}
return output;
}
}
}
Iv. Examples of Use
Txtresult.text=doscommandoutput.execute (Txtcommand.text);
Silently execute DOS commands in. NET and get the result of execution (RPM)