获取在C#中创建的进程的pid

让我们说我正在尝试使用以下代码创建一个新进程:

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(); 

在下一行中,我将尝试使用以下行获取该进程的pid:

 MessageBox.Show(p.Id); 

这一行给了我“没有进程与此对象相关联”。 错误。 有没有想过为什么会出现这种错误?

执行此System.Diagnostics.Process.GetProcessesByName(“processname”)[0] .Id。

检查Process.Start的返回值。 在某些情况下,Process.Start可以返回false,在这种情况下,不会将Id与之关联。