krolik1991
krolik1991

Reputation: 244

Exception on get process id in C#

I would like to get process ID and I try this code:

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

But I get an exception in line with myProcess.Id:

no process is associated with this object

Upvotes: 3

Views: 1044

Answers (2)

sm.abdullah
sm.abdullah

Reputation: 1802

You can try it will first get the path of the browser then it will Start it by passing URL as arguemnt.

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

it will find the default browser path what ever is.

 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;
        }

see Source

Upvotes: 1

BWA
BWA

Reputation: 5764

If you change myProcess.StartInfo.FileName = "http://somesite.com"; to myProcess.StartInfo.FileName = "cmd"; code works. I think first code doesn't create proces, it only call system to open link.

You can manualy call browser. eg.

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

Upvotes: 3

Related Questions