C# execute CMD command

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false ;     // Whether to use the operating system shell to start 
            p.StartInfo.RedirectStandardInput = true ; // Accept the input information from the calling program 
            p.StartInfo.RedirectStandardOutput = true ; // Get the output information from the calling program 
            p .StartInfo.RedirectStandardError = true ; // Redirect standard error output 
            p.StartInfo.CreateNoWindow = true ; // Do not display the program window 
            p.Start(); // Start the program

            // Send input information to the cmd window 
            p.StandardInput.WriteLine(str + " &exit " );

            p.StandardInput.AutoFlush = true ;
             // p.StandardInput.WriteLine("exit");
             // Writes the command to be executed to standard input. The use of & is the symbol of batch command, which means that the previous command will execute the following (exit) command regardless of whether it is successfully executed or not. If the exit command is not executed, the subsequent call to the ReadToEnd() method will cause suspended animation
             // Similar symbols also include && and | |The former means that the following command will be executed only if the previous command is executed successfully, and the latter means that the latter command will be executed only if the previous command fails to be executed.



            // Get the output information of the cmd window 
            string output = p.StandardOutput.ReadToEnd();

            // StreamReader reader = p.StandardOutput;
             // string line=reader.ReadLine();
             // while (!reader.EndOfStream)
             // {
             //     str += line + " ";
             //     line = reader.ReadLine( );
             // } 

            p.WaitForExit(); // Wait for the program to finish executing and exit the process 
            p.Close();


            Console.WriteLine(output);

        }
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325003910&siteId=291194637