Right now I use this to list all the applications listed in the registry for 32bit & 64.
I have seen the other examples of how to check if an application is installed without any luck.
string registryKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey);
if (key != null)
{
foreach (String a in key.GetSubKeyNames())
{
RegistryKey subkey = key.OpenSubKey(a);
Console.WriteLine(subkey.GetValue("DisplayName"));
}
}
registryKey = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
key = Registry.LocalMachine.OpenSubKey(registryKey);
if (key != null)
{
foreach (String a in key.GetSubKeyNames())
{
RegistryKey subkey = key.OpenSubKey(a);
Console.WriteLine(subkey.GetValue("DisplayName"));
}
}
So this snippet lists it all in the console window and what I am trying to do is
just find one program title out of the list of display names to see if it's installed.
The last thing I tried was
if (subkey.Name.Contains("OpenSSL"))
Console.Writeline("OpenSSL Found");
else
Console.Writeline("OpenSSL Not Found");
Anything I tried came back either false or a false positive. Is there anyone that can show me how to just grab a title out of the list?
Please don't post up the well-known private static void IsApplicationInstalled(p_name) function. It does not work for me at all.
After searching and troubleshooting, I got it to work this way:
public static bool checkInstalled (string c_name)
{
string displayName;
string registryKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey);
if (key != null)
{
foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
{
displayName = subkey.GetValue("DisplayName") as string;
if (displayName != null && displayName.Contains(c_name))
{
return true;
}
}
key.Close();
}
registryKey = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
key = Registry.LocalMachine.OpenSubKey(registryKey);
if (key != null)
{
foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
{
displayName = subkey.GetValue("DisplayName") as string;
if (displayName != null && displayName.Contains(c_name))
{
return true;
}
}
key.Close();
}
return false;
}
And I simply just call it using
if(checkInstalled("Application Name"))
This is a clean way to do this without that much code.
private static bool IsSoftwareInstalled(string softwareName)
{
var key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall") ??
Registry.LocalMachine.OpenSubKey(
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
if (key == null)
return false;
return key.GetSubKeyNames()
.Select(keyName => key.OpenSubKey(keyName))
.Select(subkey => subkey.GetValue("DisplayName") as string)
.Any(displayName => displayName != null && displayName.Contains(softwareName));
}
Call it with a if-statement:
if (IsSoftwareInstalled("OpenSSL"))
I have checked #Stellan Lindell's code and it doesn't work in all cases.
My version should work in all scenarios and checks the specific version of installed programs(x86, x64).
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Win32;
namespace Test
{
internal class Program
{
public enum ProgramVersion
{
x86,
x64
}
private static IEnumerable<string> GetRegisterSubkeys(RegistryKey registryKey)
{
return registryKey.GetSubKeyNames()
.Select(registryKey.OpenSubKey)
.Select(subkey => subkey.GetValue("DisplayName") as string);
}
private static bool CheckNode(RegistryKey registryKey, string applicationName, ProgramVersion? programVersion)
{
return GetRegisterSubkeys(registryKey).Any(displayName => displayName != null
&& displayName.Contains(applicationName)
&& displayName.Contains(programVersion.ToString()));
}
private static bool CheckApplication(string registryKey, string applicationName, ProgramVersion? programVersion)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey);
if (key != null)
{
if (CheckNode(key, applicationName, programVersion))
return true;
key.Close();
}
return false;
}
public static bool IsSoftwareInstalled(string applicationName, ProgramVersion? programVersion)
{
string[] registryKey = new [] {
#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
};
return registryKey.Any(key => CheckApplication(key, applicationName, programVersion));
}
private static void Main()
{
// Examples
Console.WriteLine("Notepad++: " + IsSoftwareInstalled("Notepad++", null));
Console.WriteLine("Notepad++(x86): " + IsSoftwareInstalled("Notepad++", ProgramVersion.x86));
Console.WriteLine("Notepad++(x64): " + IsSoftwareInstalled("Notepad++", ProgramVersion.x64));
Console.WriteLine("Microsoft Visual C++ 2009: " + IsSoftwareInstalled("Microsoft Visual C++ 2009", null));
Console.WriteLine("Microsoft Visual C-- 2009: " + IsSoftwareInstalled("Microsoft Visual C-- 2009", null));
Console.WriteLine("Microsoft Visual C++ 2013: " + IsSoftwareInstalled("Microsoft Visual C++ 2013", null));
Console.WriteLine("Microsoft Visual C++ 2012 Redistributable (x86): " + IsSoftwareInstalled("Microsoft Visual C++ 2013", ProgramVersion.x86));
Console.WriteLine("Microsoft Visual C++ 2012 Redistributable (x64): " + IsSoftwareInstalled("Microsoft Visual C++ 2013", ProgramVersion.x64));
Console.ReadKey();
}
}
}
The solution #Hyperion is ok but it has an error because for 32 bit configurations. No 64 bit registers are returned. To receive 64 bit registers, do the following:
string registryKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
RegistryKey key64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey key = key64.OpenSubKey(registryKey);
Solutions above are really good, but sometimes you have to check if product is installed also on another machine. So there is a version based on solutions above from #Stellan Lindell and #Mroczny Arturek
This method works OK for local machine and also remote machine...
public static bool IsSoftwareInstalled(string softwareName, string remoteMachine = null, StringComparison strComparison = StringComparison.Ordinal)
{
string uninstallRegKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
RegistryView[] enumValues = (RegistryView[])Enum.GetValues(typeof(RegistryView));
//Starts from 1, because first one is Default, so we dont need it...
for (int i = 1; i < enumValues.Length; i++)
{
//This one key is all what we need, because RegView will do the rest for us
using (RegistryKey key = (string.IsNullOrWhiteSpace(remoteMachine))
? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, enumValues[i]).OpenSubKey(uninstallRegKey)
: RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, remoteMachine, enumValues[i]).OpenSubKey(uninstallRegKey))
{
if (key != null)
{
if (key.GetSubKeyNames()
.Select(keyName => key.OpenSubKey(keyName))
.Select(subKey => subKey.GetValue("DisplayName") as string)
//SomeTimes we really need the case sensitive/insensitive option...
.Any(displayName => displayName != null && displayName.IndexOf(softwareName, strComparison) >= 0))
{ return true; }
}
}
}
return false;
}
The registry version is only one from two standard options.. Another option is using WMI, but the registry one is much better due to performance, so take WMI only as a alternative.
//This one does't have a case sensitive/insesitive option, but if you need it, just don't use LIKE %softwareName%
//and get all products (SELECT Name FROM Win32_Product). After that just go trough the result and compare...
public static bool IsSoftwareInstalledWMI(string softwareName, string remoteMachine = null)
{
string wmiPath = (!string.IsNullOrEmpty(remoteMachine))
? #"\\" + remoteMachine + #"\root\cimv2"
: #"\\" + Environment.MachineName + #"\root\cimv2";
SelectQuery select = new SelectQuery(string.Format("SELECT * FROM Win32_Product WHERE Name LIKE \"%{0}%\"", softwareName));
if (SelectStringsFromWMI(select, new ManagementScope(wmiPath)).Count > 0) { return true; }
return false;
}
There is my SelectStringsFromWMI method, but you can do this on your own, this is not important part of this solution. But if you are intersted, there it is...
public static List<Dictionary<string, string>> SelectStringsFromWMI(SelectQuery select, ManagementScope wmiScope)
{
List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiScope, select))
{
using (ManagementObjectCollection objectCollection = searcher.Get())
{
foreach (ManagementObject managementObject in objectCollection)
{
//With every new object we add new Dictionary
result.Add(new Dictionary<string, string>());
foreach (PropertyData property in managementObject.Properties)
{
//Always add data to newest Dictionary
result.Last().Add(property.Name, property.Value?.ToString());
}
}
return result;
}
}
}
!!UPDATE!!
Due to really bad performance, there is another improvement. Just get values async..
public static bool IsSoftwareInstalled(string softwareName, string remoteMachine = null, StringComparison strComparison = StringComparison.Ordinal)
{
string uninstallRegKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
RegistryView[] enumValues = (RegistryView[])Enum.GetValues(typeof(RegistryView));
//Starts from 1, because first one is Default, so we dont need it...
for (int i = 1; i < enumValues.Length; i++)
{
//This one key is all what we need, because RegView will do the rest for us
using (RegistryKey regKey = (string.IsNullOrWhiteSpace(remoteMachine))
? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, enumValues[i]).OpenSubKey(uninstallRegKey)
: RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, remoteMachine, enumValues[i]).OpenSubKey(uninstallRegKey))
{
if (SearchSubKeysForValue(regKey, "DisplayName", softwareName, strComparison).Result)
{ return true; }
}
}
return false;
}
And the SearchSubKeysForValue method (can be build as extension method):
public static async Task<bool> SearchSubKeysForValue(RegistryKey regKey, string valueName, string searchedValue, StringComparison strComparison = StringComparison.Ordinal)
{
bool result = false;
string[] subKeysNames = regKey.GetSubKeyNames();
List<Task<bool>> tasks = new List<Task<bool>>();
for (int i = 0; i < subKeysNames.Length - 1; i++)
{
//We have to save current value for i, because we cannot use it in async task due to changed values for it during foor loop
string subKeyName = subKeysNames[i];
tasks.Add(Task.Run(() =>
{
string value = regKey.OpenSubKey(subKeyName)?.GetValue(valueName)?.ToString() ?? null;
return (value != null && value.IndexOf(searchedValue, strComparison) >= 0);
}));
}
bool[] results = await Task.WhenAll(tasks).ConfigureAwait(false);
result = results.Contains(true);
return result;
}
I tried the solutions here, but they didnt work in some cases. The reason was, that my programm is 32 bit and runs on 64 bit Windows. With the solutions posted here a 32bit process can not check whether a 64 bit application is installed.
How to access 64 bit registry with a 32 bit process
RegistryKey.OpenBaseKey
I modifed the solutions here to get a working one for this issue:
Usage example
Console.WriteLine(IsSoftwareInstalled("Notepad++"));
Code
public static bool IsSoftwareInstalled(string softwareName)
{
var registryUninstallPath = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
var registryUninstallPathFor32BitOn64Bit = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
if (Is32BitWindows())
return IsSoftwareInstalled(softwareName, RegistryView.Registry32, registryUninstallPath);
var is64BitSoftwareInstalled = IsSoftwareInstalled(softwareName, RegistryView.Registry64, registryUninstallPath);
var is32BitSoftwareInstalled = IsSoftwareInstalled(softwareName, RegistryView.Registry64, registryUninstallPathFor32BitOn64Bit);
return is64BitSoftwareInstalled || is32BitSoftwareInstalled;
}
private static bool Is32BitWindows() => Environment.Is64BitOperatingSystem == false;
private static bool IsSoftwareInstalled(string softwareName, RegistryView registryView, string installedProgrammsPath)
{
var uninstallKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView)
.OpenSubKey(installedProgrammsPath);
if (uninstallKey == null)
return false;
return uninstallKey.GetSubKeyNames()
.Select(installedSoftwareString => uninstallKey.OpenSubKey(installedSoftwareString))
.Select(installedSoftwareKey => installedSoftwareKey.GetValue("DisplayName") as string)
.Any(installedSoftwareName => installedSoftwareName != null && installedSoftwareName.Contains(softwareName));
}
Here is my version for 64 bits
public static string[] checkInstalled(string findByName)
{
string[] info = new string[3];
string registryKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
//64 bits computer
RegistryKey key64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey key = key64.OpenSubKey(registryKey);
if (key != null)
{
foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
{
string displayName = subkey.GetValue("DisplayName") as string;
if (displayName != null && displayName.Contains(findByName))
{
info[0] = displayName;
info[1] = subkey.GetValue("InstallLocation").ToString();
info[2] = subkey.GetValue("Version").ToString();
}
}
key.Close();
}
return info;
}
you can call this method like this
string[] JavaVersion = Software.checkInstalled("Java(TM) SE Development Kit");
if the array is empty means no installation found. if it is not empty it will give you the original name, relative path, and location which in most cases that is all we are looking to get.
Related
I want to access the RegistryKeys of a remote PC in my network, if there is no terminalNumber passed as a parameter.
public LoginEntity(string ipAdress, string username, string password, string terminalNumber = "")
{
this.IpAdress = ipAdress;
this.Username = username;
this.Password = password;
if (terminalNumber == "")
{
try
{
RegistryKey rKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, IpAdress, RegistryView.Registry64);
rKey = rKey.OpenSubKey(#"SOFTWARE\Test", RegistryKeyPermissionCheck.ReadWriteSubTree);
var key = rKey.GetValue("terminalNumber", "NOTFOUND");
if (key is string)
{
if ((string)key != "NOTFOUND")
this.TerminalNumber = (string)key;
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("UnauthorizedException: Calling TerminalNumber from Remote Registry Keys");
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("IOException: Remote PC not available");
}
}
else
this.TerminalNumber = terminalNumber;
}
Due to safety reasons the Subkey in this example is called 'Test'.
But at
RegistryKey rKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, IpAdress, RegistryView.Registry64);
the application throws an UnauthorizedAccessException.
What I did:
I already run Visual Studio 2019 as an administator.
The LoginEntity was instantiated in a Task*. (As I am using WPF, I don't want my UI to freeze, so I run it in a Task).
*The Task call is located in the MainWindow()-Constructor of my WPF-Application
Task.Run(() =>
{
List<LoginEntity> loginUser = Utility.ReadLoginDataFromCsv(loginUserPath);
this.Dispatcher.Invoke(() =>
{
Listview.ItemsSource = loginUser;
lblUserLoading.Content = "";
});
});
public static List<LoginEntity> ReadLoginDataFromCsv(string path, bool ignoreFirstLine = false)
{
List<LoginEntity> list = new List<LoginEntity>();
var lines = File.ReadAllLines(path, Encoding.UTF8);
if (ignoreFirstLine)
lines = lines
.Skip(1)
.ToArray();
foreach (string line in lines)
{
var rowData = line.Split(';');
LoginEntity le = new LoginEntity(rowData[0], rowData[1], rowData[2], rowData[3]);
if (le.IpAdress != "" && le.Username != "" && le.Password != "")
list.Add(le);
}
return list;
}
Does anyone know why I get the UnAuthorizedException and how I can get rid of it?
I have the following code:
The values are displayed as follows in the debugger:
FF86_version "31.0.1"
FF86_name "Firefox"
displayFF86version "null"
displayFF86name "null"
public static bool checkFF86version(string FF86_name, string FF86_version)
{
RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
//.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
string displayFF86version;
string displayFF86name;
if (key != null)
{
foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
{
displayFF86name = subkey.GetValue("DisplayName") as string;
if (displayFF86name != null && displayFF86name.Contains(FF86_name))
{
displayFF86version = subkey.GetValue("DisplayVersion") as string;
if (displayFF86version.Equals(FF86_version))
{
var version = displayFF86version; //Comes from the Registry
var parsedversion = Version.Parse(version);
var minimumversion = new Version(FF86_version); //Static Version Check
if (parsedversion >= minimumversion)
return true;
}
}
return false;
}
}
return false;
}
I am trying to see if "Firefox" is installed. If it is detected compare the DisplayVersion to see if it is > or < the version identified as displayed below:
if (checkFF86version("Firefox", "31.0.1"))
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox is Installed and is the latest version" });
else
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox needs updated" });
I have solved this issue, I thought I would post the resolution for anyone else that may have this problem. It seems that the answers are hard to find. This may save you some time. Special thanks to "CodeK" on (CodeProject) for the help on this solution. Without him I could have never completed it.
public void GetNameAndVersion()
{
Microsoft.Win32.RegistryKey iRegKey = null;
Microsoft.Win32.RegistryKey iSubKey = null;
string eValue = null;
string eVersion = null;
string regpath = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
iRegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regpath);
string[] subkeys = iRegKey.GetSubKeyNames();
bool includes = false;
foreach (string subk in subkeys)
{
iSubKey = iRegKey.OpenSubKey(subk);
eValue = Convert.ToString(iSubKey.GetValue("DisplayName", ""));
eVersion = Convert.ToString(iSubKey.GetValue("DisplayVersion", ""));
if (eValue != null && eValue.Contains("Firefox"))
{
var version = eVersion;
var parsedversion = Version.Parse(version);
var minimumversion = new Version("35.0.1");
if (parsedversion >= minimumversion)
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox is the latest version or newer" });
else if (parsedversion < minimumversion)
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox needs reinstalled" });
else
includes = false;
}
}
}
}
}
I have solved this issue, I thought I would post the resolution for anyone else that may have this problem. It seems that the answers are hard to find. This may save you some time. Special thanks to "CodeK" on (CodeProject) for the help on this solution. Without him I could have never completed it.
public void GetNameAndVersion()
{
Microsoft.Win32.RegistryKey iRegKey = null;
Microsoft.Win32.RegistryKey iSubKey = null;
string eValue = null;
string eVersion = null;
string regpath = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
iRegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regpath);
string[] subkeys = iRegKey.GetSubKeyNames();
bool includes = false;
foreach (string subk in subkeys)
{
iSubKey = iRegKey.OpenSubKey(subk);
eValue = Convert.ToString(iSubKey.GetValue("DisplayName", ""));
eVersion = Convert.ToString(iSubKey.GetValue("DisplayVersion", ""));
if (eValue != null && eValue.Contains("Firefox"))
{
var version = eVersion;
var parsedversion = Version.Parse(version);
var minimumversion = new Version("35.0.1");
if (parsedversion >= minimumversion)
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox is the latest version or newer" });
else if (parsedversion < minimumversion)
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox needs reinstalled" });
else
includes = false;
}
}
}
}
}
I'm trying to develop a method to read the programs installed on the machine.
public void refreshProgramsFromWindows () {
string SoftwareKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products";
RegistryKey rk = default(RegistryKey);
rk = Registry.LocalMachine.OpenSubKey(SoftwareKey);
//string skname = null;
string sname = string.Empty;
// New list from scratch
this.installedSoftwareList = new List<software>();
// Object software info
software aSoftware = new software();
foreach (string skname in rk.GetSubKeyNames())
{
// Reset software info
aSoftware.reset();
try
{
// Name of the programm
sname = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("DisplayName").ToString();
aSoftware.name = sname;
// Write program to the list
installedSoftwareList.Add(aSoftware);
}
catch (Exception ex)
{
}
}
Net Framework is 4.5 and i'm over Windows 7/8. When i debug this piece of code var rk is null, and it's throwing a null reference exception in the foreach. The app manifest is set to require admin Privileges, so the registry is readable. What is the problem?
Thanks you in advance.
Cheers.
64 bits registry problem:
Added (to handle 64 bit registry):
public static RegistryKey GetRegistryKey()
{
return GetRegistryKey(null);
}
public static RegistryKey GetRegistryKey(string keyPath)
{
RegistryKey localMachineRegistry
= RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
Environment.Is64BitOperatingSystem
? RegistryView.Registry64
: RegistryView.Registry32);
return string.IsNullOrEmpty(keyPath)
? localMachineRegistry
: localMachineRegistry.OpenSubKey(keyPath);
}
public static object GetRegistryValue(string keyPath, string keyName)
{
RegistryKey registry = GetRegistryKey(keyPath);
return registry.GetValue(keyName);
}
And changed:
rk = Registry.LocalMachine.OpenSubKey(SoftwareKey);
to
rk = GetRegistryKey(SoftwareKey);
And now it works.
I would like to know if there's a way to list the SQL Server instances installed on the local computer.
SqlDataSourceEnumerator and EnumAvailableSqlServers don't do the trick as I don't need the instances that are over the local network.
Direct access to Windows Registry isn't the recommended solution by MS, because they can change keys/paths. But I agree that SmoApplication.EnumAvailableSqlServers() and SqlDataSourceEnumerator.Instance fails providing instances on 64-bit platforms.
Getting data from Windows Registry, keep in mind the difference in Registry access between x86 and x64 platforms. 64-bit edition of Windows stores data in different parts of system registry and combines them into views. So using RegistryView is essential.
using Microsoft.Win32;
RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
RegistryKey instanceKey = hklm.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
if (instanceKey != null)
{
foreach (var instanceName in instanceKey.GetValueNames())
{
Console.WriteLine(Environment.MachineName + #"\" + instanceName);
}
}
}
If you are looking for 32-bit instances on a 64-bit OS (pretty weird, but possible), you will need to look:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
You could call EnumAvailableSQlServers with a localOnly = True
public static DataTable EnumAvailableSqlServers(bool localOnly)
See MSDN docs for EnumAvailableSqlServers
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
foreach (System.Data.DataRow row in table.Rows)
{
if (row["ServerName"] != DBNull.Value && Environment.MachineName.Equals(row["ServerName"].ToString()))
{
string item = string.Empty;
item = row["ServerName"].ToString();
if(row["InstanceName"] != DBNull.Value || !string.IsNullOrEmpty(Convert.ToString(row["InstanceName"]).Trim()))
{
item += #"\" + Convert.ToString(row["InstanceName"]).Trim();
}
listview1.Items.Add(item);
}
}
you can use registry to get sql server instance name in local system
private void LoadRegKey()
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names");
foreach (string sk in key.GetSubKeyNames())
{
RegistryKey rkey = key.OpenSubKey(sk);
foreach (string s in rkey.GetValueNames())
{
MessageBox.Show("Sql instance name:"+s);
}
}
}
Combined several methods:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.Wmi;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using Microsoft.Win32;
namespace SqlServerEnumerator
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, Func<List<string>>> methods = new Dictionary<string, Func<List<string>>>
{
{"CallSqlBrowser", GetLocalSqlServerInstancesByCallingSqlBrowser},
{"CallSqlWmi32", GetLocalSqlServerInstancesByCallingSqlWmi32},
{"CallSqlWmi64", GetLocalSqlServerInstancesByCallingSqlWmi64},
{"ReadRegInstalledInstances", GetLocalSqlServerInstancesByReadingRegInstalledInstances},
{"ReadRegInstanceNames", GetLocalSqlServerInstancesByReadingRegInstanceNames},
{"CallSqlCmd", GetLocalSqlServerInstancesByCallingSqlCmd},
};
Dictionary<string, List<string>> dictionary = methods
.AsParallel()
.ToDictionary(v => v.Key, v => v.Value().OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList());
foreach (KeyValuePair<string, List<string>> pair in dictionary)
{
Console.WriteLine(string.Format("~~{0}~~", pair.Key));
pair.Value.ForEach(v => Console.WriteLine(" " + v));
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static List<string> GetLocalSqlServerInstancesByCallingSqlBrowser()
{
DataTable dt = SmoApplication.EnumAvailableSqlServers(true);
return dt.Rows.Cast<DataRow>()
.Select(v => v.Field<string>("Name"))
.ToList();
}
private static List<string> GetLocalSqlServerInstancesByCallingSqlWmi32()
{
return LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture.Use32bit);
}
private static List<string> GetLocalSqlServerInstancesByCallingSqlWmi64()
{
return LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture.Use64bit);
}
private static List<string> LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture providerArchitecture)
{
try
{
ManagedComputer managedComputer32 = new ManagedComputer();
managedComputer32.ConnectionSettings.ProviderArchitecture = providerArchitecture;
const string defaultSqlInstanceName = "MSSQLSERVER";
return managedComputer32.ServerInstances.Cast<ServerInstance>()
.Select(v =>
(string.IsNullOrEmpty(v.Name) || string.Equals(v.Name, defaultSqlInstanceName, StringComparison.OrdinalIgnoreCase)) ?
v.Parent.Name : string.Format("{0}\\{1}", v.Parent.Name, v.Name))
.OrderBy(v => v, StringComparer.OrdinalIgnoreCase)
.ToList();
}
catch (SmoException ex)
{
Console.WriteLine(ex.Message);
return new List<string>();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new List<string>();
}
}
private static List<string> GetLocalSqlServerInstancesByReadingRegInstalledInstances()
{
try
{
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\InstalledInstances
string[] instances = null;
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server"))
{
if (rk != null)
{
instances = (string[])rk.GetValue("InstalledInstances");
}
instances = instances ?? new string[] { };
}
return GetLocalSqlServerInstances(instances);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new List<string>();
}
}
private static List<string> GetLocalSqlServerInstancesByReadingRegInstanceNames()
{
try
{
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL
string[] instances = null;
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"))
{
if (rk != null)
{
instances = rk.GetValueNames();
}
instances = instances ?? new string[] { };
}
return GetLocalSqlServerInstances(instances);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new List<string>();
}
}
private static List<string> GetLocalSqlServerInstances(string[] instanceNames)
{
string machineName = Environment.MachineName;
const string defaultSqlInstanceName = "MSSQLSERVER";
return instanceNames
.Select(v =>
(string.IsNullOrEmpty(v) || string.Equals(v, defaultSqlInstanceName, StringComparison.OrdinalIgnoreCase)) ?
machineName : string.Format("{0}\\{1}", machineName, v))
.ToList();
}
private static List<string> GetLocalSqlServerInstancesByCallingSqlCmd()
{
try
{
// SQLCMD -L
int exitCode;
string output;
CaptureConsoleAppOutput("SQLCMD.exe", "-L", 200, out exitCode, out output);
if (exitCode == 0)
{
string machineName = Environment.MachineName;
return output.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(v => v.Trim())
.Where(v => !string.IsNullOrEmpty(v))
.Where(v => string.Equals(v, "(local)", StringComparison.Ordinal) || v.StartsWith(machineName, StringComparison.OrdinalIgnoreCase))
.Select(v => string.Equals(v, "(local)", StringComparison.Ordinal) ? machineName : v)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
return new List<string>();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new List<string>();
}
}
private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)
{
using (Process process = new Process())
{
process.StartInfo.FileName = exeName;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
output = process.StandardOutput.ReadToEnd();
bool exited = process.WaitForExit(timeoutMilliseconds);
if (exited)
{
exitCode = process.ExitCode;
}
else
{
exitCode = -1;
}
}
}
}
}
public static string SetServer()
{
string serverName = #".\SQLEXPRESS";
var serverNameList = SqlHelper.ListLocalSqlInstances();
if (serverNameList != null)
{
foreach (var item in serverNameList)
serverName = #"" + item;
}
return serverName;
}
To get local server names
How can I find of all the browsers and their details that are installed on a machine.
A quick google search gave me Finding All Installed Browsers in Windows XP and Vista
In the application I’ve been working on, I needed to find all browsers that are installed on a user’s machine. The best way to go about this is to look in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet. This is where browser manufacturers are told to put their information, per this MSDN article.
A short answer:
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
{
RegistryKey webClientsRootKey = hklm.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
if (webClientsRootKey != null)
foreach (var subKeyName in webClientsRootKey.GetSubKeyNames())
if (webClientsRootKey.OpenSubKey(subKeyName) != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
{
string commandLineUri = (string)webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(null);
//your turn
}
}
Simple example of an application (WPF) to launch all installed browsers:
cs:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
namespace WpfApplication94
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<ViewerApplication> viewers = new List<ViewerApplication>();
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
{
RegistryKey webClientsRootKey = hklm.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
if (webClientsRootKey != null)
foreach (var subKeyName in webClientsRootKey.GetSubKeyNames())
if (webClientsRootKey.OpenSubKey(subKeyName) != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
{
string commandLineUri = (string)webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(null);
if (string.IsNullOrEmpty(commandLineUri))
continue;
commandLineUri = commandLineUri.Trim("\"".ToCharArray());
ViewerApplication viewer = new ViewerApplication();
viewer.Executable = commandLineUri;
viewer.Name = (string)webClientsRootKey.OpenSubKey(subKeyName).GetValue(null);
viewers.Add(viewer);
}
}
this.listView.ItemsSource = viewers;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Process.Start(((sender as Control).Tag as ViewerApplication).Executable, #"http://news.google.de");
}
}
public class ViewerApplication
{
public string Name { get; set; }
public string Executable { get; set; }
public Icon Icon
{
get { return System.Drawing.Icon.ExtractAssociatedIcon(this.Executable); }
}
public ImageSource ImageSource
{
get
{
ImageSource imageSource;
using (Bitmap bmp = Icon.ToBitmap())
{
var stream = new MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
imageSource = BitmapFrame.Create(stream);
}
return imageSource;
}
}
}
}
xaml:
<Window x:Class="WpfApplication94.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<Button Tag="{Binding}" Click="Button_Click">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Window>
result:
Scan the contents of the Program Files folder for the filenames of known browser executables.
Necromancing, as the provided answers are incomplete.
First:
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet.
won't get you all browsers.
If you're in a corporate environment, the user will not have admin rights.
If Google-Chrome and/or Chromium are installed that way (don't know if FF works like that), then the key will only be in HK_Current_User.
Also, this doesn't cover non-windows operating systems.
You'll need elaborate code to determine and cover all package-management system on Linux + Mac systems.
Here code for Windows + Debian-based Linuces
PlatformInfo:
using System.Diagnostics;
namespace PlatformInfo
{
public delegate int BrowserRatingCallback_t(string packageName);
public class BrowserInfo : System.IComparable<BrowserInfo>
{
public string Name;
public string Path;
public int Preference;
public int CompareTo(BrowserInfo other)
{
if (this == null || other == null)
return 0;
int pref = this.Preference.CompareTo(other.Preference);
if (pref != 0)
return pref;
return string.Compare(this.Name, other.Name, true);
} // End Function CompareTo
public static int DefaultBrowserRating(string packageName)
{
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Google")) return 1;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Chromium")) return 2;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Opera")) return 3;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Firefox")) return 4;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Midori")) return 5;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Safari")) return 9000;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Edge")) return 9998;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Explorer")) return 9999;
return 9997;
}
public static System.Collections.Generic.List<BrowserInfo> GetPreferableBrowser()
{
return GetPreferableBrowser(BrowserInfo.DefaultBrowserRating);
}
public static System.Collections.Generic.List<BrowserInfo> GetPreferableBrowser(BrowserRatingCallback_t browserRatingCallback)
{
if (System.Environment.OSVersion.Platform != System.PlatformID.Unix)
return Win.GetPreferableBrowser(browserRatingCallback);
// ELSE: Linux / Unix / MacOS
if (DistroInfo.PackageManager == DistroInfo.PackageManager_t.dpkg)
return dpkg.GetInstalledBrowsers(browserRatingCallback);
return new System.Collections.Generic.List<BrowserInfo>();
}
} // End Class BrowserInfo : System.IComparable<BrowserInfo>
public class DistroInfo
{
public enum Distro_t : int
{
Debian
,Ubuntu
,Mint
,Arch
,Gentoo
,CentOS
,Fedora
,RedHat
,Mageia
,Suse
,Mandrake
,YellowDog
,Slackware
,SunJDS
,Solaris
,UnitedLinux
,Unknown
} // End Enum Distro_t
public enum PackageManager_t : int
{
dpkg
,rpm
,portage
,pacman
,pkgtool
,ips
,unknown
} // End Enum PackageManager_t
public enum DistroFamily_t : int
{
Debian, RedHat, Unknown
} // End Enum DistroFamily_t
public static DistroFamily_t DistroFamily
{
get {
if (Distro == Distro_t.Ubuntu)
return DistroFamily_t.Debian;
if (Distro == Distro_t.Debian)
return DistroFamily_t.Debian;
if (Distro == Distro_t.Mint)
return DistroFamily_t.Debian;
if (Distro == Distro_t.RedHat)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.CentOS)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.Fedora)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.Suse)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.Mageia)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.Mandrake)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.YellowDog)
return DistroFamily_t.RedHat;
return DistroFamily_t.Unknown;
}
} // End Property DistroFamily
public static PackageManager_t PackageManager
{
get {
if (DistroFamily == DistroFamily_t.Debian)
return PackageManager_t.dpkg;
if (DistroFamily == DistroFamily_t.RedHat)
return PackageManager_t.rpm;
if(Distro == Distro_t.Arch)
return PackageManager_t.pacman;
if(Distro == Distro_t.Gentoo)
return PackageManager_t.portage;
if(Distro == Distro_t.Slackware)
return PackageManager_t.pkgtool;
if(Distro == Distro_t.Solaris)
return PackageManager_t.ips;
if(Distro == Distro_t.SunJDS)
return PackageManager_t.ips;
return PackageManager_t.unknown;
}
} // End Property PackageManager
// Release Files in /etc (from Unix.com)
// Novell SuSE---> /etc/SuSE-release
// Red Hat--->/etc/redhat-release, /etc/redhat_version
// Fedora-->/etc/fedora-release
// Slackware--->/etc/slackware-release, /etc/slackware-version
// Old Debian--->/etc/debian_release, /etc/debian_version
// New Debian--->/etc/os-release
// Mandrake--->/etc/mandrake-release
// Yellow dog-->/etc/yellowdog-release
// Sun JDS--->/etc/sun-release
// Solaris/Sparc--->/etc/release
// Gentoo--->/etc/gentoo-release
// cat /etc/issue
// CentOS Linux release 6.0 (Final)
// Kernel \r on an \m
// cat /proc/version
// uname -a
// If you are in a container, beware cat /proc/version will give the host distro, not the container one.
// http://unix.stackexchange.com/questions/35183/how-do-i-identify-which-linux-distro-is-running
public static Distro_t Distro
{
get{
string issue = null;
if (System.IO.File.Exists("/etc/issue"))
issue = System.IO.File.ReadAllText("/etc/issue", System.Text.Encoding.UTF8);
if (EmbeddedWebServer.StringHelpers.Contains(issue, "Ubuntu"))
return Distro_t.Ubuntu;
if (System.IO.File.Exists("/etc/os-release"))
return Distro_t.Debian; // New Debian
if (System.IO.File.Exists("/etc/debian_release"))
return Distro_t.Debian; // Old Debian
if (System.IO.File.Exists("/etc/gentoo-release"))
return Distro_t.Gentoo; // Not yet supported
if (System.IO.File.Exists("/etc/SuSE-release"))
return Distro_t.Suse;
if (EmbeddedWebServer.StringHelpers.Contains(issue, "CentOS"))
return Distro_t.CentOS;
if (System.IO.File.Exists("/etc/fedora-release"))
return Distro_t.Fedora;
if (System.IO.File.Exists("/etc/redhat_version"))
return Distro_t.Fedora;
// Unsupported
if (System.IO.File.Exists("/etc/mandrake-release"))
return Distro_t.Mandrake;
if (System.IO.File.Exists("/etc/slackware-release"))
return Distro_t.Slackware;
if (System.IO.File.Exists("/etc/yellowdog-release"))
return Distro_t.YellowDog;
if (System.IO.File.Exists("/etc/yellowdog-release"))
return Distro_t.YellowDog;
if (System.IO.File.Exists("/etc/sun-release"))
return Distro_t.SunJDS;
if (System.IO.File.Exists("/etc/release"))
return Distro_t.Solaris;
if (System.IO.File.Exists("/etc/UnitedLinux-release"))
return Distro_t.Solaris;
return Distro_t.Unknown;
} // End Get
} // End Property Distro
} // End Class DistroInfo
public class dpkg
{
public static bool HasDPKG()
{
// if (System.IO.File.Exists("/usr/bin/dpkg")) return true;
if (DistroInfo.PackageManager == DistroInfo.PackageManager_t.dpkg)
return true;
return false;
} // End Function HasDPKG
public static bool IsPackageInstalled(string packageName)
{
Process process = new Process();
process.StartInfo.FileName = "dpkg";
process.StartInfo.Arguments = "-s \"" + packageName + "\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
process.WaitForExit();
int result = process.ExitCode;
if (result == 0)
return true;
return false;
} // End Function IsPackageInstalled
public static string GetExecutable(string packageName)
{
Process process = new Process();
process.StartInfo.FileName = "dpkg";
process.StartInfo.Arguments = "-L \"" + packageName + "\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (output != null)
output = output.Replace("\r", "\n");
string[] lines = output.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
string executable = null;
foreach (string line in lines)
{
if (line.IndexOf("/bin/") != -1)
{
executable = line;
break;
}
}
return executable;
} // End Function GetExecutable
public static System.Collections.Generic.List<BrowserInfo> GetInstalledBrowsers()
{
return GetInstalledBrowsers(BrowserInfo.DefaultBrowserRating);
} // End Function GetInstalledBrowsers
public static System.Collections.Generic.List<BrowserInfo> GetInstalledBrowsers(BrowserRatingCallback_t browserRatingCallback )
{
System.Collections.Generic.List<BrowserInfo> ls = new System.Collections.Generic.List<BrowserInfo>();
System.Collections.Generic.List<string> packageList = GetPossibleBrowsers();
foreach (string packageName in packageList)
{
if (IsPackageInstalled(packageName))
{
int sort = browserRatingCallback(packageName);
ls.Add(new BrowserInfo()
{
Name = packageName
,Path = GetExecutable(packageName)
,Preference = sort
});
} // End if (isPackageInstalled(packageName))
} // Next packageName
ls.Sort();
return ls;
} // End Function GetInstalledBrowsers
public static System.Collections.Generic.List<string> GetPossibleBrowsers()
{
return SearchPackages("www-browser");
} // End Function GetPossibleBrowsers
public static System.Collections.Generic.List<string> SearchPackages(string categoryName)
{
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
Process process = new Process(); // e.g. apt-cache search www-browser
process.StartInfo.FileName = "apt-cache";
process.StartInfo.Arguments = "search \"" + categoryName + "\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (output != null)
output = output.Replace("\r", "\n");
string[] lines = output.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (string.IsNullOrEmpty(line))
continue;
int pos = line.IndexOf(" ");
if (pos < 0)
continue;
string packageName = line.Substring(0, pos);
ls.Add(packageName);
} // Next line
return ls;
} // End Function SearchPackages
} // End Class dpkg
public class Win
{
public static System.Collections.Generic.List<BrowserInfo> GetPreferableBrowser(BrowserRatingCallback_t browserRatingCallback)
{
System.Collections.Generic.List<BrowserInfo> ls = new System.Collections.Generic.List<BrowserInfo>();
if (System.Environment.OSVersion.Platform == System.PlatformID.Unix)
return ls;
using (Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine)
{
Microsoft.Win32.RegistryKey webClientsRootKey = hklm.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
if (webClientsRootKey != null)
foreach (var subKeyName in webClientsRootKey.GetSubKeyNames())
if (webClientsRootKey.OpenSubKey(subKeyName) != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
{
string commandLineUri = (string)webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(null);
if (string.IsNullOrEmpty(commandLineUri))
continue;
commandLineUri = commandLineUri.Trim("\"".ToCharArray());
// viewer.Executable = commandLineUri;
string Name = (string)webClientsRootKey.OpenSubKey(subKeyName).GetValue(null);
ls.Add(new BrowserInfo()
{
Name = Name
,
Path = commandLineUri
,
Preference = browserRatingCallback(Name)
});
}
} // End Using
using (Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.CurrentUser)
{
Microsoft.Win32.RegistryKey webClientsRootKey = hklm.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
if (webClientsRootKey != null)
foreach (var subKeyName in webClientsRootKey.GetSubKeyNames())
if (webClientsRootKey.OpenSubKey(subKeyName) != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
{
string commandLineUri = (string)webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(null);
if (string.IsNullOrEmpty(commandLineUri))
continue;
commandLineUri = commandLineUri.Trim("\"".ToCharArray());
// viewer.Executable = commandLineUri;
string Name = (string)webClientsRootKey.OpenSubKey(subKeyName).GetValue(null);
ls.Add(new BrowserInfo()
{
Name = Name
,
Path = commandLineUri
,
Preference = browserRatingCallback(Name)
});
}
} // End Using
ls.Sort();
return ls;
} // End Function GetPreferableBrowser
}
public class rpm
{
public rpm()
{
throw new System.NotImplementedException("TODO");
}
// # rpm -q --whatprovides webclient
//links-graphic-2.1-0.pre11.1mdk
//lynx-2.8.5-1mdk
//links-2.1-0.pre13.3mdk
//kdebase-common-3.2.3-134.8.101mdk
//mozilla-1.7.2-12.2.101mdk
//epiphany-1.2.8-4.2.101mdk
//wget-1.9.1-4.2.101mdk
// Another rough method is apropos
// This lists unexpected results too, and misses firefox as well as konqueror, who didn't filled the man-pages correctly.
//snx]->~ > apropos browser
//alevt (1) - X11 Teletext browser
//amrecover (8) - Amanda index database browser
//elinks (1) - lynx-like alternative character mode WWW browser
//gnome-moz-remote (1) - remote control of browsers.
//goad-browser (1) - Graphical GOAD browser
//links (1) - lynx-like alternative character mode WWW browser
//LinNeighborhood (1) - an SMB Network Browser
//lynx (1) - a general purpose distributed information browser for the World Wide Web
//mozilla-1.5 (1) - a Web browser for X11 derived from Netscape Communicator
//opera (1) - a graphical web browser
//sensible-browser (1) - sensible editing, paging, and web browsing
//smbtree (1) - A text based smb network browser
//www (1) - the W3C Line Mode Browser.
//www-browser (1) - a general purpose distributed information browser for the World Wide Web
//xfhelp (1) - lauches an HTML browser to display online documentation for
// "The Cholesterol Free Desktop Environment"
//viewres (1x) - graphical class browser for Xt
//htsserver (1) - offline browser server : copy websites to a local directory
//httrack (1) - offline browser : copy websites to a local directory
//webhttrack (1) - offline browser : copy websites to a local directory
} // End Class RPM
} // End Namespace
String-Helpers
using System;
using System.Collections.Generic;
using System.Text;
namespace EmbeddedWebServer
{
internal class StringHelpers
{
public static bool Contains(string source, string value)
{
if (source == null || value == null)
return false;
return System.Globalization.CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, value, System.Globalization.CompareOptions.IgnoreCase) != -1;
}
}
}
And this is the actual usage:
public void OpenBrowser()
{
System.Collections.Generic.List<PlatformInfo.BrowserInfo> bi = PlatformInfo.BrowserInfo.GetPreferableBrowser();
string url = "\"" + "http://127.0.0.1:" + this.m_Port.ToString() + "/Index.htm\"";
if (bi.Count > 0)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName =bi[0].Path;
psi.Arguments = url;
System.Diagnostics.Process.Start(psi);
return;
}
System.Diagnostics.Process.Start(url);
} // End Sub OpenBrowser
This solution seems to work for me:
RegistryKey browserKeys;
//on 64bit the browsers are in a different location
browserKeys = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\WOW6432Node\Clients\StartMenuInternet");
if (browserKeys == null)
browserKeys = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
string[] browserNames = browserKeys.GetSubKeyNames();
Enjoy coding! Chagbert.