您的位置:首页 > 编程语言 > C#

.NET C# 如何监控并及时的显示另一个控制台Console的输出

2011-07-18 21:11 435 查看
这个话题已经很多前辈已经提及或者说明过,不过今天我还是来炒下冷饭.
很多人在论坛上问及,在不修改现有项目的前提下如何监控其控制台输出?
这里我们就需要用到ProcessStartInfo中的RedirectStandardOutput以及StandardOutput属性
关于StandardOutput以及RedirectStandardOutput,我不在此罗嗦,有兴趣的可以参考下MSDN:
http://msdn.microsoft.com/zh-cn/library/system.diagnostics.processstartinfo.redirectstandardoutput(v=vs.80).aspx

而且其中微软已经给了Stream.ReadToEnd的方法来读取所有的输出.
以下的的例子中提及的是如何逐行输出以及如何及时的输出.
首先准备一个被监控的控制台进程,以下例子为逐行输出
代码如下:

static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Testing in :" + DateTime.Now.ToString());
System.Threading.Thread.Sleep(50);
}

}

其监控逐行输出代码如下:

static void Main(string[] args)
{
StreamReader sr;
ProcessStartInfo s = new ProcessStartInfo();
s.RedirectStandardInput = true;
s.RedirectStandardOutput = true;
s.UseShellExecute = false;
s.FileName = @"d:\OutputRepeat.exe";
Process p = Process.Start(s);
sr = p.StandardOutput;
while (!sr.EndOfStream)
{
string str = sr.ReadLine();
Console.WriteLine(str);
}
p.WaitForExit();
p.Close();
}


而有些人会提及如果被监控程式非逐行输出,而其又要很及时的监控这个输出,该怎么办?
别急,看以下例子,我们只需要小小的修改一个地方,把Stream.ReadLine改成Stream.Read即可

准备一个被监控的控制台进程,以下例子为非逐行输出代码如下:
static void Main(string[] args)
{
while (true)
{
Console.Write("Testing in :" + DateTime.Now.ToString());
System.Threading.Thread.Sleep(50);
}

}

其及时监控输出代码如下:
static void Main(string[] args)
{
StreamReader sr;
ProcessStartInfo s = new ProcessStartInfo();
s.RedirectStandardInput = true;
s.RedirectStandardOutput = true;
s.UseShellExecute = false;
s.FileName = @"E:\CSharp\OutputRepeat\bin\Release\OutputRepeat.exe";
Process p = Process.Start(s);
sr = p.StandardOutput;
while (!sr.EndOfStream)
{
char[] bs = new char[16];
int i = sr.Read(bs, 0, 16);
foreach (char o in bs)
{
Console.Write(o);
}
}
p.WaitForExit();
p.Close();
}

这样就实现了及时快速的监控其他控制台程式的输出.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: