King
King

Reputation: 113

How to get the process Id safely after process.Start()?

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.

Upvotes: 2

Views: 1189

Answers (1)

usr
usr

Reputation: 171178

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.

Upvotes: 1

Related Questions