using
System;
using
System.Windows.Forms;
namespace
WindowsApplication8
...
{
public partial class Form1 : Form
...{
public Form1()
...{
InitializeComponent();
}
delegate void dReadLine(string strLine);
private void excuteCommand(string strFile, string args, dReadLine onReadLine)
...{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo();
p.StartInfo.FileName = strFile;
p.StartInfo.Arguments = args;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
System.IO.StreamReader reader = p.StandardOutput;//截取输出流
string line = reader.ReadLine();//每次读取一行
while (!reader.EndOfStream)
...{
onReadLine(line);
line = reader.ReadLine();
}
p.WaitForExit();
}
private void button1_Click(object sender, EventArgs e)
...{
excuteCommand("ipconfig", "", new dReadLine(PrintMessage));
}
private void PrintMessage(string strLine)
...{
this.textBox1.Text += strLine + " ";
}
}
}
本文介绍了一个使用C#实现的简单示例,通过该示例可以了解如何利用System.Diagnostics命名空间中的Process类来执行外部命令并读取其标准输出。此方法适用于希望在Windows应用程序中集成命令行工具功能的开发者。

2065

被折叠的 条评论
为什么被折叠?



