开发者

Getting a pid of a process created in C#

开发者 https://www.devze.com 2022-12-25 04:10 出处:网络
Lets say that I\'m trying to create a new process with the following code: System.Diagnostics.Process p = new System.Diagnostics.Process();

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. A开发者_运维问答ny idea as to why this error occurs?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消