现在的位置: 首页 > 综合 > 正文

[C# FAQ]C#代码中如何启动另一个应用程序或批处理程序?

2012年10月21日 ⁄ 综合 ⁄ 共 1307字 ⁄ 字号 评论关闭

original URL: How can I run another application or batch file from my Visual C# .NET code?
Posted by: Duncan Mackenzie, MSDN
This post applies to Visual C# .NET 2002/2003


如果你要运行一个命令行程序,或者打开一个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。这样你更有可能给用户带来他们所希望得到的体验,
并且可以利用具有最新连接信息的浏览器。

抱歉!评论已关闭.