C's method of executing the DOS command
- 2020-12-10 00:48:36
- OfStack
The example in this article shows how C# executes the DOS command. Share to everybody for everybody reference. Specific implementation methods are as follows:
In the c# program, it is sometimes used to call the cmd command to do 1 of these things. This article describes the following method to achieve the function of c# to execute the DOS command and return the result.
//dosCommand Dos Command statement
public string Execute(string dosCommand)
{
return Execute(dosCommand, 10);
}
/// <summary>
/// perform DOS Command, return DOS Output of a command
/// </summary>
/// <param name="dosCommand">dos The command </param>
/// <param name="milliseconds"> The time to wait for the command to execute in milliseconds,
/// If I set it to 0 , then wait indefinitely </param>
/// <returns> return DOS Output of a command </returns>
public static string Execute(string command, int seconds)
{
string output = ""; // Output string
if (command != null && !command.Equals(""))
{
Process process = new Process();// Create process objects
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";// Sets the command to be executed
startInfo.Arguments = "/C " + command;// " /C "Means to quit immediately after executing an order
startInfo.UseShellExecute = false;// Start without using the system shell
startInfo.RedirectStandardInput = false;// Do not redirect the input
startInfo.RedirectStandardOutput = true; // Redirected output
startInfo.CreateNoWindow = true;// Not creating a window
process.StartInfo = startInfo;
try
{
if (process.Start())// Start process
{
if (seconds == 0)
{
process.WaitForExit();// Wait indefinitely for the process to end
}
else
{
process.WaitForExit(seconds); // Wait for the process to finish for the specified number of milliseconds
}
output = process.StandardOutput.ReadToEnd();// Read the output of the process
}
}
catch
{
}
finally
{
if (process != null)
process.Close();
}
}
return output;
}
Hopefully this article has helped you with your C# programming.