[C# FAQ]C#代碼中如何啟動另一個應用程式或批次程式?

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.