Hi @john zyd , Welcome to Microsoft Q&A, you could try the following code to get what you wanted.
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Execute(""));//(Your dos command)
}
//dosCommand Dos command statement
public string Execute(string dosCommand)
{
return Execute(dosCommand, 10);
}
/// <summary>
/// Execute the DOS command and return the output of the DOS command
/// </summary>
/// <param name="dosCommand">dos command</param>
/// <param name="milliseconds">Waiting for the command execution time (unit: milliseconds),
/// If set to 0, wait indefinitely</param>
/// <returns>Returns the output of the DOS command</returns>
public static string Execute(string command, int seconds)
{
string output = "";
//output string
if (command != null && !command.Equals(""))
{
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 " + command;
//"/C" means exit immediately after executing the command
startInfo.UseShellExecute = false;
//Do not use the system shell to start
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())//Start the process
{
if (seconds == 0)
{
process.WaitForExit();
//Here infinite waiting for the process to end
} else
{
process.WaitForExit(seconds);
//Wait for the process to end, the waiting time is the specified milliseconds
}
output = process.StandardOutput.ReadToEnd();
//Read the output of the process
}
}
catch
{
}
finally
{
if (process != null)
process.Close();
}
}
return output;
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.