7

Lets say that I'm trying to create a new process with the following code:

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
p.StartInfo.FileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\AwesomeFile.exe";
p.StartInfo.Arguments = "parameter1 parameter2";
p.StartInfo.CreateNoWindow = true;
p.Start();

and right in the next line, I'll try to get a pid of that process with the following line:

MessageBox.Show(p.Id);

This line is giving me the "No process is associated with this object." error. Any idea as to why this error occurs?

screenshot345
  • 598
  • 3
  • 9
  • 18

2 Answers2

10

Check the return value of Process.Start. In some cases, Process.Start can return false, in which case no Id will be associated with it.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
4

Do this System.Diagnostics.Process.GetProcessesByName("processname")[0].Id.

Raj Kaimal
  • 8,304
  • 27
  • 18
  • Thank you for your response. Is there a way to identify different processes of the same name? Lets say that I have two iexplore processes running, both were initially executed with different urls as parameters. How would I know which one is which in the array? – screenshot345 Mar 29 '10 at 18:01
  • I noticed this command: System.Diagnostics.Process.GetProcessesByName("processname")[0].StartInfo which includes argument parameter, which would be great, but it turns out to be empty on a file that was not executed by C#. Is there any way to fix it? – screenshot345 Mar 29 '10 at 19:15