usingSystem.Diagnostics; Public classCmdhelper {Private Static stringCmdpath =@"C:\Windows\System32\cmd.exe"; /// <summary> ///Execute cmd command///For multiple commands, use the Batch command connector:/// <! [Cdata[ ///&: Execute two commands at a time///|: The output from the previous command as input to the next command///&&: When the command before && is successful, the command after && is executed/// || : when | | The previous command failed before execution | | After the command]]>///others please Baidu/// </summary> /// <param name= "cmd" ></param> /// <param name= "Output" ></param> Public Static voidRuncmd (stringCmd out stringoutput) {cmd= cmd. Trim (). TrimEnd ('&') +"&exit";//Note: The exit command is executed regardless of whether the command succeeds or not, and is in suspended animation when the ReadToEnd () method is called . using(Process p =NewProcess ()) {p.StartInfo.FileName=Cmdpath; P.startinfo.useshellexecute=false;//whether to start with the operating system shellP.startinfo.redirectstandardinput =true;//accept input from the calling programP.startinfo.redirectstandardoutput =true;//get output information from the calling programP.startinfo.redirectstandarderror =true;//REDIRECT standard error OutputP.startinfo.createnowindow =true;//do not show program windowP.start ();//Start the program//writing commands to the cmd windowp.standardinput.writeline (CMD); P.standardinput.autoflush=true; //gets the output information of the cmd windowOutput =P.standardoutput.readtoend (); p.WaitForExit ();//wait for the program to finish executing the exit processP.close (); }}} Use Example 1: Display ipconfig informationstringcmd =@"Ipconfig/all"; Example 2: Open the VS2010 command promptstringcmd =@"C:&CD C:\Program Files (x86) \microsoft Visual Studio 10.0\vc&vcvarsall.bat"; Example 3: Use the Sn.exe tool to generate a key pair and displaystringcmd =@"C:&CD C:\Program Files (x86) \microsoft Visual Studio 10.0\vc&vcvarsall.bat&sn-k D:\LICBASE.SNK&SN -P d:\LicBase.snk d:\licbasepubkey.snk&sn-tp d:\LicBasePubKey.snk"; CallstringOutput =""; Cmdhelper.runcmd (cmd, outoutput); MessageBox.Show (output);
C # call the cmd command