C#中获取进程ID的异常

时间:2016-01-04 15:54:45

标签: c# exception process

我想获取进程ID并尝试此代码:

Process myProcess = new Process();
myProcess.StartInfo.FileName = "http://somesite.com";
myProcess.Start();
logs.logging("Afetr Open" + myProcess.Id, 8);

但是我得到一个与myProcess.Id符合的例外:

  

没有与此对象关联的进程

2 个答案:

答案 0 :(得分:2)

如果您将myProcess.StartInfo.FileName = "http://somesite.com";更改为myProcess.StartInfo.FileName = "cmd";代码有效。 我认为第一个代码不会创建进程,它只调用系统来打开链接。

您可以手动调用浏览器。例如。

Process myProcess = Process.Start("iexplore", "http://somesite.com");        
var id = myProcess.Id;

答案 1 :(得分:1)

您可以尝试先获取浏览器的路径,然后通过将URL作为arguemnt传递来启动它。

    var path = GetStandardBrowserPath();
    var process = Process.Start(path , "http://www.google.com");
    int processId = process.Id ;

它会找到默认的浏览器路径。

 private static string GetStandardBrowserPath()
        {
            string browserPath = string.Empty;
            RegistryKey browserKey = null;

            try
            {
                //Read default browser path from Win XP registry key
                browserKey = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);

                //If browser path wasn't found, try Win Vista (and newer) registry key
                if (browserKey == null)
                {
                    browserKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ;
                }

                //If browser path was found, clean it
                if (browserKey != null)
                {
                    //Remove quotation marks
                    browserPath = (browserKey.GetValue(null) as string).ToLower().Replace("\"", "");

                    //Cut off optional parameters
                    if (!browserPath.EndsWith("exe"))
                    {
                        browserPath = browserPath.Substring(0, browserPath.LastIndexOf(".exe") + 4);
                    }

                    //Close registry key
                    browserKey.Close();
                }
            }
            catch
            {
                //Return empty string, if no path was found
                return string.Empty;
            }
            //Return default browsers path
            return browserPath;
        }

请参阅Source