2018/10/17

[C#] WPF Auto Launch exe File

讓程式可以自動執行某個exe檔案
1. 在執行前可以先檢查檔案是否存在,避免找不到檔案造成當機。
2. 接著還要判斷exe是否已經執行,避免重複執行一樣的。
3. 都確認後再來自動執行myRun.exe檔案。
可以利用MessageBox.Show來提示檢查結果,而且這樣寫會比較安全&完整一點。

完整程式碼:
  1. var filePath = "..\\myRun.exe";
  2.  
  3. // 1. check if file is exist or not
  4. if (!File.Exists(filePath))
  5. {
  6. MessageBox.Show("The myRun.exe file does not exist! Cannot launch.");
  7. }
  8. else
  9. {
  10. // 2. check if file is already running or not
  11. Process[] pname = Process.GetProcessesByName("myRun");
  12. if (pname.Length > 0)
  13. {
  14. MessageBox.Show("myRun is already running");
  15. }
  16. else
  17. {
  18. Process.Start(filePath); // 3. run the exe
  19. }
  20. }


End

沒有留言:

張貼留言