现在的位置: 首页 > 综合 > 正文

C#代码打开CMD.EXE 执行 DIR命令,并接收返回值

2013年08月25日 ⁄ 综合 ⁄ 共 637字 ⁄ 字号 评论关闭
		Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";//要执行的程序名称
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;//可能接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
                p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                p.Start();//启动程序
                //向CMD窗口发送输入信息:
                p.StandardInput.WriteLine("dir"); 
                //获取CMD窗口的输出信息:
                StreamReader sr = p.StandardOutput;
                string sOutput = sr.ReadLine();
                //以下两句至关重要,如果不设置,则会死机,因为流读取到最后一行后还会接到读取一行,由于没有数据供其读取,则会一直等待
                Thread.Sleep(5000); 
                p.Kill();
                while (sOutput != null)
                {
                    this.textBox1.Text += sOutput + "\r\n";
                    if (!sr.EndOfStream)
                        sOutput = sr.ReadLine();
                    else
                        sOutput = null;
                }
                sr.Close();
                p.Close();

以上只是本人在项目遇到的一些浅显难题,公布出来供大家参考

抱歉!评论已关闭.