获取在 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);
这一行给我“没有进程与该对象相关联。”错误。知道为什么会出现此错误吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查 Process.Start 的返回值。在某些情况下,Process.Start 可能返回 false,在这种情况下,不会有任何 Id 与其关联。
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.
这样做
System.Diagnostics.Process.GetProcessesByName("进程名称")[0].Id。
Do this
System.Diagnostics.Process.GetProcessesByName("processname")[0].Id.