Ioan Cucu
Ioan Cucu

Reputation: 23

How to determine the default browser with C#?

I have the following code in C# .NET Core Windows 10:

    public string getBrowser()
    {
        string browserName = "iexplore.exe";
        using (RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey(@"\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice"))
        {
            if (userChoiceKey != null)
            {
                object progIdValue = userChoiceKey.GetValue("Progid");
                if (progIdValue != null)
                {
                    if (progIdValue.ToString().ToLower().Contains("chrome"))
                        browserName = "chrome.exe";
                    else if (progIdValue.ToString().ToLower().Contains("firefox"))
                        browserName = "firefox.exe";
                    else if (progIdValue.ToString().ToLower().Contains("opera"))
                        browserName = "opera.exe";
                }
            }
        }

        return browserName;
    }

The problem is that

userChoiceKey

is always null.

I practically copy paste the path from the registry Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice

And still not working.

Any help will be highly appreciated.

Thanks in advance!

Upvotes: 2

Views: 886

Answers (1)

Raul Marquez
Raul Marquez

Reputation: 1116

Try this:

internal string GetSystemDefaultBrowser()
    {
        string name = string.Empty;
        RegistryKey regKey = null;

        try
        {
            var regDefault = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.htm\\UserChoice", false);
            var stringDefault = regDefault.GetValue("ProgId");

            regKey = Registry.ClassesRoot.OpenSubKey(stringDefault + "\\shell\\open\\command", false);
            name = regKey.GetValue(null).ToString().ToLower().Replace("" + (char)34, "");

            if (!name.EndsWith("exe"))
                name = name.Substring(0, name.LastIndexOf(".exe") + 4);

        }
        catch (Exception ex)
        {
            name = string.Format("ERROR: An exception of type: {0} occurred in method: {1} in the following module: {2}", ex.GetType(), ex.TargetSite, this.GetType());
        }
        finally
        {
            if (regKey != null)
                regKey.Close();
        }

        return name;
    }

Upvotes: 4

Related Questions