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。這樣你更有可能給使用者帶來他們所希望得到的體驗,
並且可以利用具有最新串連資訊的瀏覽器。