调用控制台应用程序并获得程序的输出信息

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

前一阵在网上看到有网友想实现这样的功能。因此特写了这样一段代码。

using System.Diagnostics;

class Class1

{

/// <summary>

/// 应用程序的主入口点。

/// </summary>

[STAThread]

static void Main(string[] args)

{

//创建一个新的进程对象

Process myCmdProcess = new Process();

//当进程退出时要处理的代码,注册一个事件

myCmdProcess.Exited += new System.EventHandler(myCmdProcess_exited);

//要调用的应用程序cmd.exe

myCmdProcess.StartInfo.FileName = "cmd";

//将参数传给要调用的应用程序 /C 执行字符串指定的命令然后终断 ,调用ipconfig ,同时将ipconfig处理的结果输出到应用程序文件夹下test.txt.

//此文件不存在,则自动创建

myCmdProcess.StartInfo.Arguments = "/C ipconfig >test.txt";

myCmdProcess.StartInfo.RedirectStandardOutput = true;

myCmdProcess.StartInfo.UseShellExecute = false;

myCmdProcess.StartInfo.CreateNoWindow = true;

myCmdProcess.EnableRaisingEvents =true;

myCmdProcess.Start();

Console.Read();

}

private static void myCmdProcess_exited(object sender, System.EventArgs e)

{

//这里的代码相信大家都能看懂了。就是读test.txt文件里的内容,显示出来

try

{

System.IO.StreamReader myFile = new System.IO.StreamReader("test.txt");

string myString = myFile.ReadToEnd();

myFile.Close();

Console.WriteLine(myString);

}

catch(Exception excpt)

{

Console.WriteLine( excpt.Message);

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有