C#获取进程id异常

Exception on get process id in C#

我想获取进程 ID 并尝试使用以下代码:

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

但是我得到一个符合myProcess.Id的异常:

no process is associated with this object

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

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

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

您可以尝试它首先获取浏览器的路径,然后通过将 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