1. 在執行前可以先檢查檔案是否存在,避免找不到檔案造成當機。
2. 接著還要判斷exe是否已經執行,避免重複執行一樣的。
3. 都確認後再來自動執行myRun.exe檔案。
可以利用MessageBox.Show來提示檢查結果,而且這樣寫會比較安全&完整一點。
完整程式碼:
- var filePath = "..\\myRun.exe";
- // 1. check if file is exist or not
- if (!File.Exists(filePath))
- {
- MessageBox.Show("The myRun.exe file does not exist! Cannot launch.");
- }
- else
- {
- // 2. check if file is already running or not
- Process[] pname = Process.GetProcessesByName("myRun");
- if (pname.Length > 0)
- {
- MessageBox.Show("myRun is already running");
- }
- else
- {
- Process.Start(filePath); // 3. run the exe
- }
- }
End
沒有留言:
張貼留言