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

发布于 2024-08-26 14:43:48 字数 624 浏览 3 评论 0原文

假设我正在尝试使用以下代码创建一个新进程:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏末的微笑 2024-09-02 14:43:48

检查 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.

草莓酥 2024-09-02 14:43:48

这样做
System.Diagnostics.Process.GetProcessesByName("进程名称")[0].Id。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文