C#之CMD

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Threading;

namespace KFC_v1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int Error;
        
        //CMD主命令
        private void cmd(string a)
        {
            Error = 0;
            Process myProcess = new Process();
            myProcess.StartInfo.FileName = "cmd.exe ";//DOS控制平台 
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.StartInfo.RedirectStandardInput = true;
            myProcess.StartInfo.RedirectStandardOutput = true;
            myProcess.StartInfo.RedirectStandardError = true;
            myProcess.Start();
            StreamWriter sIn = myProcess.StandardInput;//标准输入流 
            sIn.AutoFlush = true;
            StreamReader sOut = myProcess.StandardOutput;//标准输出流 
            StreamReader sErr = myProcess.StandardError;//标准错误流 
            sIn.Write(a + System.Environment.NewLine);//DOS控制平台上的命令 
            sIn.Write("dir " + System.Environment.NewLine);//DOS控制平台上的命令 
            sIn.Write("exit " + System.Environment.NewLine);
            string s = sOut.ReadToEnd();//读取执行DOS命令后输出信息 
            string er = sErr.ReadToEnd();//读取执行DOS命令后错误信息 
            //MessageBox.Show(er);
            if ((er == null) || (er.Length != 0))
            {
                Error = 1;
                MessageBox.Show("CMD run error,please confirm the Adminstrator right or other issues\nCMD运行出错,请检查是否在具有管理员权限或者其他问题", "出错啦", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //richTextBox1.AppendText(s);
            //richTextBox1.AppendText(er);
            if (myProcess.HasExited == false)
            {
                myProcess.Kill();
            }
            sIn.Close();
            sOut.Close();
            sErr.Close();
            myProcess.Close();
        }
原文地址:https://www.cnblogs.com/Liangw/p/2559908.html