当前位置:编程学习 > C#/ASP.NET >>

C# 调用个cmd程序,不段接收该程序运行的信息,该怎么做?

需要在C#中调用dos进程,比如ping 127.0.0.1 -t -l 1000,要在C#程序中不段接收ping发出的数据,请问该怎样做? --------------------编程问答--------------------

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();
}

}

--------------------编程问答-------------------- TO:iraya
这代码一直在用,但不能实时得到ping返回的信息,ping加入-t参数后会不段返回信息的! --------------------编程问答-------------------- 要不就直接找一段用C#实现ping的方法 --------------------编程问答-------------------- c# 调用cmd执行命令 要等cmd执行完毕才能获得返回的信息,好像你这个实时获取的需求是没办法满足的。。。 --------------------编程问答-------------------- TO:acqy
ping只是比喻啦,是其它无界面的命令行输出程序

TO:nkboy
可是很多程序都是这样调用而实时不停得到输出信息啊,例如MyEntunnel --------------------编程问答-------------------- up --------------------编程问答-------------------- mark --------------------编程问答-------------------- 说个思路,你要他的输出,他又是第3方程序,所以你不能指望他告诉你。所以你要把它读出来。而且似乎他是不断的反馈信息的。所以把上边的代码改改,启动该程序后不要等待他退出,设置一个时钟,周期性的读取他的StandardOutput --------------------编程问答--------------------            StreamReader standReader = CProcess.StandardOutput;//截取标准输出流            
            while (!standReader.EndOfStream)
            {
                line = standReader.ReadLine();
                CommonMethod.WriteEntry("CompilerSpider", "info", line);
            }

用这个 --------------------编程问答-------------------- 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();


补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,