2

When a program is copied to many locations and then is started independently, sometimes error may appear:

ProcessStartInfo startInfo = new ProcessStartInfo(exePath);
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.ErrorDialog = false;

Process process = new Process() { StartInfo = startInfo };
bool isStarted = process.Start();
int processId = process.Id; // Failed as bellow When the isStarted is false

System.InvalidOperationException: No process is associated with this object.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
King
  • 113
  • 6
  • possible duplicate of [getting PID of process started by Process.start()](http://stackoverflow.com/questions/12892268/getting-pid-of-process-started-by-process-start) – Daniel Casserly Jul 08 '15 at 10:05
  • It's just likely that your process has started, but encountered an immediate failure, like unhandled exception, and terminated immediately. In this case the bool flag for `IsStarted` will be set to false and you don't get process id. If you really-really need this captured, i'd assume you may need some sort of a driver to subscribe to a process start kernel call. You may be out of luck otherwise. In most situations you don't *really* need to capture an attempt to start a process. – oleksii Jul 08 '15 at 10:26
  • @King Add process.Exited event to get idea when it exited `process.Exited += Process_Exited;` – NASSER Jul 08 '15 at 10:41
  • Normally, the Process class should hold a handle to that process. This stabilizes the ID. This should just work. Is that your real code? – usr Jul 08 '15 at 12:13
  • Are you really starting exe files? I don't know how isStarted could ever be false for those. Set UseShellExecute = false. – usr Jul 08 '15 at 12:15

1 Answers1

1

Since you are starting EXE files you don't need the UseShellExecute feature. For some unfathomable reason UseShellExecute is set to true by default. Using it entails a lot of complexity.

Set UseShellExecute to false and Start should always return true. Then, the ID should always be valid. Be sure to dispose of the Process instance.

usr
  • 168,620
  • 35
  • 240
  • 369