zoukankan      html  css  js  c++  java
  • C#-执行cmd命令,获取结果

     

    using System;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace EFDemo {
        public partial class ExecCmd : Form {
            public ExecCmd() {
                InitializeComponent();
                Control.CheckForIllegalCrossThreadCalls = false;
            }
    
            private void button1_Click(object sender, EventArgs e) {
                if (pro == null) { MessageBox.Show("进程未开启"); return; }
                Task.Factory.StartNew(() => {
    
                    AppendLog("执行命令: " + textBox1.Text);
                    pro.StandardInput.WriteLine(textBox1.Text);
                    //pro.StandardInput.WriteLine("exit");
                    pro.StandardInput.AutoFlush = true;
                    //获取cmd窗口的输出信息
    
                    string output = "";
                    while (true) {
                        output = pro.StandardOutput.ReadLine();
                        AppendLog(output);
                    }
                });
            }
    
            public void AppendLog(string str) {
                textBox2.AppendText("
    " + str);
            }
    
    
            //CMD进程
            System.Diagnostics.Process pro = null;
            //启动线程
            private void button2_Click(object sender, EventArgs e) {
    
                if (pro != null) {
                    MessageBox.Show("只能运行一个程序!", "请确定", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
    
                AppendLog("初始化参数");
                pro = new System.Diagnostics.Process();
                pro.StartInfo.FileName = "cmd.exe";
                pro.StartInfo.UseShellExecute = false;
                pro.StartInfo.RedirectStandardError = true;
                pro.StartInfo.RedirectStandardInput = true;
                pro.StartInfo.RedirectStandardOutput = true;
                pro.StartInfo.CreateNoWindow = true;
                //pro.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                AppendLog("启动");
                pro.Start();
            }
    
            //关闭
            private void button3_Click(object sender, EventArgs e) {
                if (pro != null) {
                    pro.Close();
                    pro = null;
                    AppendLog("关闭");
                }
            }
    
    
    
        }
    }
    
  • 相关阅读:
    Linux服务器使用tar加密压缩文件
    ssh-copy-id使用非默认22端口
    Nginx日志分割脚本
    MySQL的yum源
    vSphere Client开启虚拟机提示:出现了常规系统错误: 由于目标计算机积极拒绝,无法连接。
    ESXi主机遗忘密码重置密码
    扩容swap交换分区空间
    ESXi上的固态硬盘识别为非SSD
    VMware Vcenter Server 6.0忘记密码
    Centos6与Centos7区别
  • 原文地址:https://www.cnblogs.com/grj001/p/12223437.html
Copyright © 2011-2022 走看看