private string RunCmd(string command)
{
// 实例化一个Process类,启动一个独立进程
Process p = new Process();
// 加入参数 "/c " + 要执行的命令来执行一个dos命令, "/c "代表执行参数指定的命令后关闭cmd.exe /k参数则不关闭cmd.exe
p.StartInfo.FileName = "cmd.exe";           //设定运行程序名
//p.StartInfo.Arguments = "/c " + command;    //设定执行参数
p.StartInfo.UseShellExecute = false;        //关闭Shell使用
p.StartInfo.RedirectStandardInput = true;   //重定向标准输入
p.StartInfo.RedirectStandardOutput = true;  //重定向标准输出
p.StartInfo.RedirectStandardError = true;   //重定向错误输出
p.StartInfo.CreateNoWindow = true;          //设置不显示窗口

try
{
p.Start();   //启动 p.StandardInput.WriteLine(command); //也可以用这种方式输入要执行的命令
p.StandardInput.WriteLine("exit"); //要记得加上Exit要不然下一行命令执行的时候会死机
p.WaitForExit(); //等待控制台程序执行完成
return p.StandardOutput.ReadToEnd(); //从输出流取得命令执行结果
}
catch (System.Exception ex)
{
return ex.Message;
}
finally
{
p.Close();
}}

解决方案 »

  1.   

    TO:iraya
    这代码一直在用,但不能实时得到ping返回的信息,ping加入-t参数后会不段返回信息的!
      

  2.   

    要不就直接找一段用C#实现ping的方法
      

  3.   

    c# 调用cmd执行命令 要等cmd执行完毕才能获得返回的信息,好像你这个实时获取的需求是没办法满足的
      

  4.   

    TO:acqy
    ping只是比喻啦,是其它无界面的命令行输出程序TO:nkboy
    可是很多程序都是这样调用而实时不停得到输出信息啊,例如MyEntunnel
      

  5.   

    说个思路,你要他的输出,他又是第3方程序,所以你不能指望他告诉你。所以你要把它读出来。而且似乎他是不断的反馈信息的。所以把上边的代码改改,启动该程序后不要等待他退出,设置一个时钟,周期性的读取他的StandardOutput
      

  6.   

               StreamReader standReader = CProcess.StandardOutput;//截取标准输出流            
                while (!standReader.EndOfStream)
                {
                    line = standReader.ReadLine();
                    CommonMethod.WriteEntry("CompilerSpider", "info", line);
                }用这个
      

  7.   

    Process p = new Process();
                p.StartInfo = new ProcessStartInfo();
                p.StartInfo.FileName = "ping";
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.UseShellExecute = false;
                p.Start();
                StreamReader reader = p.StandardOutput;//截取输出流
                string input = reader.ReadLine();//每次读取一行
                while (!reader.EndOfStream)
                ...{
                    input = reader.ReadLine();
                }
                p.WaitForExit();