Getting a pid of a process created in C#

旧时模样 提交于 2019-12-30 08:53:31

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/2539920/getting-a-pid-of-a-process-created-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!