C# 调用 CMD 命令

来源:互联网 发布:室内设计画图软件 编辑:程序博客网 时间:2024/05/22 03:10
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace CmdTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void CmdTest_Click(object sender, EventArgs e)
        {
            Process p = new Process();  // 初始化新的进程
            p.StartInfo.FileName = "CMD.EXE"; //创建CMD.EXE 进程
            p.StartInfo.RedirectStandardInput = true; //重定向输入
            p.StartInfo.RedirectStandardOutput = true;//重定向输出
            p.StartInfo.UseShellExecute = false; // 不调用系统的Shell
            p.StartInfo.RedirectStandardError = true; // 重定向Error
            p.StartInfo.CreateNoWindow = true; //不创建窗口
            p.Start(); // 启动进程
            p.StandardInput.WriteLine("dir c:\\"); // Cmd 命令
            p.StandardInput.WriteLine("exit"); // 退出
            string s = p.StandardOutput.ReadToEnd(); //将输出赋值给 S
            p.WaitForExit();  // 等待退出
            richTextBox1.Text = s; // 在Richtextbox1 中显示 输出内容
            
            
        }
    }
}
0 0