public void processCommand(string commandName, string argument)
{
ProcessStartInfo start = new ProcessStartInfo(commandName);//设置运行的命令行文件问ping.exe文件,这个文件系统会自己找到
//如果是其它exe文件,则有可能需要指定详细路径,如运行winRar.exe
start.WorkingDirectory = @"F:\TRY\";
start.Arguments = argument;//设置命令参数
start.CreateNoWindow = true;//不显示dos命令行窗口
start.RedirectStandardOutput = true;//
start.RedirectStandardInput = true;//
start.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
textBox2.AppendText(start.WorkingDirectory + "\n");
Process p = Process.Start(start);
StreamReader reader = p.StandardOutput;//截取输出流
string line = reader.ReadLine();//每次读取一行
while (!reader.EndOfStream)
{
textBox2.AppendText(line + "\n");
line = reader.ReadLine();
}
p.WaitForExit();//等待程序执行完退出进程
p.Close();//关闭进程
reader.Close();//关闭流
}
如果你要运行一个命令行程序,或者打开一个windows应用程序,或者打开默认的web浏览器或email客户端,..你应该如何在你的C#代码中实现这个功能呢?
以下这些例子完成相同的任务,你可以使用System.Diagnostics.Process中的类和方法完成这些任务,甚至作的更多。
例1:不管输出结果,仅仅是运行一个命令行程序:
private void simpleRun_Click(object sender, System.EventArgs e){
System.Diagnostics.Process.Start(@"C:\listfiles.bat");
}
例2. 得到程序运行结果等待直到程序中止(同步运行程序)private void runSyncAndGetResults_Click(object sender, System.EventArgs e){
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo(@"C:\listfiles.bat");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = listFiles.StandardOutput;
listFiles.WaitForExit(2000);
if (listFiles.HasExited)
{
string output = myOutput.ReadToEnd();
this.processResults.Text = output;
}
}
例3. 使用用户机器里的默认浏览器显示URL
private void launchURL_Click(object sender, System.EventArgs e){
string targetURL = @http://www.duncanmackenzie.net;
System.Diagnostics.Process.Start(targetURL);
}
我的看法是,同样是打开浏览器显示URL,使用例3种的方法比启动IE并以URL作为参数要来得合理。
例3的代码将会启动用户的默认浏览器,而并不总是IE。这样你更有可能给用户带来他们所希望得到的体验,
并且可以利用具有最新连接信息的浏览器。