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

scr*_*345 6 c# pid process

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

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();
Run Code Online (Sandbox Code Playgroud)

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

MessageBox.Show(p.Id);
Run Code Online (Sandbox Code Playgroud)

这一行给了我"没有进程与此对象相关联".错误.知道为什么会出现这个错误吗?

Ree*_*sey 10

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


Raj*_*mal 4

执行此操作 System.Diagnostics.Process.GetProcessesByName("processname")[0].Id。