2010-03-29 148 views
6

讓我們說,我想創建一個具有以下代碼的新工藝:獲得在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); 

此行給我「沒有進程與此對象關聯」。錯誤。任何想法爲什麼發生這個錯誤?

回答

3

這樣做 System.Diagnostics.Process.GetProcessesByName(「processname」)[0] .Id。

+0

謝謝你的迴應。 有沒有一種方法來識別同名的不同進程?假設我有兩個iexplore進程正在運行,它們最初都是以不同的url作爲參數執行的。我怎麼知道哪一個是陣列中的哪一個? – screenshot345 2010-03-29 18:01:28

+0

我注意到此命令: System.Diagnostics.Process.GetProcessesByName(「processname」)[0] .StartInfo ,其包括參數參數,這將是巨大的,但它原來是空的上,這不是一個文件由C#執行。有什麼方法可以解決它嗎? – screenshot345 2010-03-29 19:15:25

10

檢查返回值Process.Start。在某些情況下,Process.Start可以返回false,在這種情況下,Id將不會與其關聯。