「C#」执行Cmd命令系列

- 姿势一

参照:
https://blog.csdn.net/LiHaoYang11/article/details/53302875
https://blog.csdn.net/yysyangyangyangshan/article/details/6799489
http://www.cnblogs.com/babycool/p/3570648.html
https://www.cnblogs.com/njl041x/p/3881550.html

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;  //执行CMD要引入的

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process CmdProcess = new Process();
            CmdProcess.StartInfo.FileName = "cmd.exe";

            CmdProcess.StartInfo.CreateNoWindow = true;         // 不创建新窗口    
            CmdProcess.StartInfo.UseShellExecute = false;       //不启用shell启动进程  
            CmdProcess.StartInfo.RedirectStandardInput = true;  // 重定向输入    
            CmdProcess.StartInfo.RedirectStandardOutput = true; // 重定向标准输出    
            CmdProcess.StartInfo.RedirectStandardError = true;  // 重定向错误输出

            CmdProcess.StartInfo.Arguments = "/c " +  textBox1.Text;
            CmdProcess.Start();
            string result = CmdProcess.StandardOutput.ReadToEnd();
            CmdProcess.StandardInput.AutoFlush = true;
            if ((result.Length) > 5)
            {
                textBox2.Text = result;

            }
            else { textBox2.Text =   CmdProcess.StandardError.ReadToEnd(); }



            CmdProcess.WaitForExit();

            CmdProcess.Close();



        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

猜你喜欢

转载自blog.csdn.net/iverson1180/article/details/81022211