1. 程式人生 > >C#:Process類操控cmd命令,執行並列印

C#:Process類操控cmd命令,執行並列印

1.引入名稱空間

using System.Diagnostics;

2.程式碼如下:

using System;
using System.Diagnostics;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e) {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe"; //待執行的檔案路徑
            p.StartInfo.UseShellExecute = false; //重定向輸出,這個必須為false
            p.StartInfo.RedirectStandardError = true; //重定向錯誤流
            p.StartInfo.RedirectStandardInput = true; //重定向輸入流
            p.StartInfo.RedirectStandardOutput = true; //重定向輸出流
            p.StartInfo.CreateNoWindow = true; //不啟動cmd黑框框
            String pingstr;
            p.Start();
            p.StandardInput.WriteLine("ping -n 1 " + "127.0.0.1"); //向cmd視窗傳送輸入資訊   ping 一次
            //p.StandardInput.WriteLine("helps"); //向cmd視窗傳送輸入資訊  helps命令不存在,所以會有錯誤資訊
            //p.StandardInput.WriteLine("help");
            p.StandardInput.WriteLine("exit");  //這句一定要有 退出
            String strRst = p.StandardOutput.ReadToEnd(); //獲取cmd處理輸出資訊
            String error = p.StandardError.ReadToEnd(); //獲取錯誤資訊
            MessageBox.Show(strRst +  "\n錯誤資訊:" + error) ;
        }
    }
}