`
hulunberbus
  • 浏览: 859286 次
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多

前一阵在网上看到有网友想实现这样的功能。因此特写了这样一段代码。
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);
}

}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics