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.
Related
I'm trying to find executable files for games; however some are nested (For example Ark: Survival Evolved) (A:\Steam Games\steamapps\common\ARK\ShooterGame\Binaries\Win64\ShooterGame.exe)
I've spent ages trying to find a way to only find the executables which are relevant.
This link shows games when we don't search recursively. It finds most, but not all .exe's
This link shows games searching recursively, but also shows a bunch of binaries/redist exes.
Initially I tried excluding "bin","binary","binaries","redist" folders but that then didn't give me Ark: Survival Evolved for example.
I also considered filtering the .exe's based on their size, but Aperture Tag has a QC_Eyes.exe at 3055KB, but Tomb Raider II.exe is 892KB.
Here's the method I'm using to find the steam installation directory, and check the libraryfolders.vdf file for where the library locations are. For now I'm just writing to console so that I can see what the outputs are.
If anyone has any tips on how I can find the right files for the right games it would be much appreciated. Thanks
public void SearchSteam()
{
steamGameDirs.Clear();
string steam32 = "SOFTWARE\\VALVE\\";
string steam64 = "SOFTWARE\\Wow6432Node\\Valve\\";
string steam32path;
string steam64path;
string config32path;
string config64path;
RegistryKey key32 = Registry.LocalMachine.OpenSubKey(steam32);
RegistryKey key64 = Registry.LocalMachine.OpenSubKey(steam64);
foreach(string k32subKey in key32.GetSubKeyNames())
{
using (RegistryKey subKey = key32.OpenSubKey(k32subKey))
{
steam32path = subKey.GetValue("InstallPath").ToString();
config32path = steam32path + "/steamapps/libraryfolders.vdf";
if (File.Exists(config32path))
{
string[] configLines = File.ReadAllLines(config32path);
foreach(var item in configLines)
{
Console.WriteLine("32: " + item);
}
}
}
}
foreach(string k64subKey in key64.GetSubKeyNames())
{
using (RegistryKey subKey = key64.OpenSubKey(k64subKey))
{
steam64path = subKey.GetValue("InstallPath").ToString();
config64path = steam64path + "/steamapps/libraryfolders.vdf";
string driveRegex = #"[A-Z]:\\";
if (File.Exists(config64path))
{
string[] configLines = File.ReadAllLines(config64path);
foreach (var item in configLines)
{
Console.WriteLine("64: " + item);
Match match = Regex.Match(item, driveRegex);
if(item != string.Empty && match.Success)
{
string matched = match.ToString();
string item2 = item.Substring(item.IndexOf(matched));
item2 = item2.Replace("\\\\", "\\");
steamGameDirs.Add(item2);
}
}
steamGameDirs.Add(steam64path + "\\steamapps\\common\\");
}
}
}
foreach(string item in steamGameDirs)
{
string GameTitle;
string[] Executables = new string[0];
string[] steamGames = Directory.GetDirectories(item);
foreach (var dir in steamGames)
{
string title = dir.Substring(dir.IndexOf("\\common\\"));
string[] titlex = title.Split('\\');
title = titlex[2].ToString();
GameTitle = title;
Console.WriteLine("Title: " + GameTitle);
Console.WriteLine("Directory: " + dir);
string[] executables = Directory.GetFiles(dir, "*.exe", SearchOption.AllDirectories);
int num = 0;
foreach (var ex in executables)
{
//add "ex" to Executables[] if poss
Console.WriteLine(ex);
num++;
}
}
}
}
I've managed to do what I can, so first I detect where steam is installed through the registry, then I check /steamapps/libraryfolders.vdf for where the users libraries are, then check those libraries for any "top level" executables. The program then lets the user select their own exe if one isn't found in the top directory.
Seems like the best solution for now as the steamfiles module isn't currently active.
public void SearchSteam()
{
steamGameDirs.Clear();
string steam32 = "SOFTWARE\\VALVE\\";
string steam64 = "SOFTWARE\\Wow6432Node\\Valve\\";
string steam32path;
string steam64path;
string config32path;
string config64path;
RegistryKey key32 = Registry.LocalMachine.OpenSubKey(steam32);
RegistryKey key64 = Registry.LocalMachine.OpenSubKey(steam64);
if (key64.ToString() == null || key64.ToString() == "")
{
foreach (string k32subKey in key32.GetSubKeyNames())
{
using (RegistryKey subKey = key32.OpenSubKey(k32subKey))
{
steam32path = subKey.GetValue("InstallPath").ToString();
config32path = steam32path + "/steamapps/libraryfolders.vdf";
string driveRegex = #"[A-Z]:\\";
if (File.Exists(config32path))
{
string[] configLines = File.ReadAllLines(config32path);
foreach (var item in configLines)
{
Console.WriteLine("32: " + item);
Match match = Regex.Match(item, driveRegex);
if (item != string.Empty && match.Success)
{
string matched = match.ToString();
string item2 = item.Substring(item.IndexOf(matched));
item2 = item2.Replace("\\\\", "\\");
item2 = item2.Replace("\"", "\\steamapps\\common\\");
steamGameDirs.Add(item2);
}
}
steamGameDirs.Add(steam32path + "\\steamapps\\common\\");
}
}
}
}
foreach(string k64subKey in key64.GetSubKeyNames())
{
using (RegistryKey subKey = key64.OpenSubKey(k64subKey))
{
steam64path = subKey.GetValue("InstallPath").ToString();
config64path = steam64path + "/steamapps/libraryfolders.vdf";
string driveRegex = #"[A-Z]:\\";
if (File.Exists(config64path))
{
string[] configLines = File.ReadAllLines(config64path);
foreach (var item in configLines)
{
Console.WriteLine("64: " + item);
Match match = Regex.Match(item, driveRegex);
if(item != string.Empty && match.Success)
{
string matched = match.ToString();
string item2 = item.Substring(item.IndexOf(matched));
item2 = item2.Replace("\\\\", "\\");
item2 = item2.Replace("\"", "\\steamapps\\common\\");
steamGameDirs.Add(item2);
}
}
steamGameDirs.Add(steam64path + "\\steamapps\\common\\");
}
}
}
}
Attached the code so others can see how I've done it. I know it's not the best but it's working
The keydata seems to be in the appinfo.vdf file. So a somewhat working code to get the correct EXE file for steam games is as follows. Where the game is an EA game with a pointer to an URL or there is no data in the appinfo.vdf a fallback to your previous solution could be used. If anyone got a good parser of the appinfo.vdf the code would be better and not as hacky as the "IndexOf" solution.
GetSteamPath() in the below code can be updated to fetch from registry.
I am going to use that code to fix those petchy steam links that goes back to that anonymous globe-url icon.
(Written in .Net 5.0 - seems IndexOf for .4.7.2 is quirky. doesnt like \x00 I think)
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace SteamAppsParser
{
class Program
{
static void Main(string[] args)
{
var libs = GetSteamLibs();
var apps = GetSteamApps(libs);
}
static List<AppInfo> GetSteamApps(List<string> steamLibs)
{
var apps = new List<AppInfo>();
foreach (var lib in steamLibs)
{
var appMetaDataPath = Path.Combine(lib, "SteamApps");
var files = Directory.GetFiles(appMetaDataPath, "*.acf");
foreach (var file in files)
{
var appInfo = GetAppInfo(file);
if (appInfo != null)
{
apps.Add(appInfo);
}
}
}
return apps;
}
static AppInfo GetAppInfo(string appMetaFile)
{
var fileDataLines = File.ReadAllLines(appMetaFile);
var dic = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var line in fileDataLines)
{
var match = Regex.Match(line, #"\s*""(?<key>\w+)""\s+""(?<val>.*)""");
if (match.Success)
{
var key = match.Groups["key"].Value;
var val = match.Groups["val"].Value;
dic[key] = val;
}
}
AppInfo appInfo = null;
if (dic.Keys.Count > 0)
{
appInfo = new AppInfo();
var appId = dic["appid"];
var name = dic["name"];
var installDir = dic["installDir"];
var path = Path.GetDirectoryName(appMetaFile);
var libGameRoot = Path.Combine(path, "common", installDir);
if (!Directory.Exists(libGameRoot)) return null;
appInfo.Id = appId;
appInfo.Name = name;
appInfo.Manifest = appMetaFile;
appInfo.GameRoot = libGameRoot;
appInfo.InstallDir = installDir;
appInfo.SteamUrl = $"steam://runsteamid/{appId}";
//if (appInfo.Name.StartsWith("Sid Meier"))
appInfo.Executable = GetExecutable(appInfo);
}
return appInfo;
}
static string _appInfoText = null;
static string GetExecutable(AppInfo appInfo)
{
if (_appInfoText == null)
{
var appInfoFile = Path.Combine(GetSteamPath(), "appcache", "appinfo.vdf");
var bytes = File.ReadAllBytes(appInfoFile);
_appInfoText = Encoding.UTF8.GetString(bytes);
}
var startIndex = 0;
int maxTries = 50;
var fullName = "";
do
{
var startOfDataArea = _appInfoText.IndexOf($"\x00\x01name\x00{appInfo.Name}\x00", startIndex);
if (startOfDataArea < 0 && maxTries == 50) startOfDataArea = _appInfoText.IndexOf($"\x00\x01gamedir\x00{appInfo.Name}\x00", startIndex); //Alternative1
if (startOfDataArea < 0 && maxTries == 50) startOfDataArea = _appInfoText.IndexOf($"\x00\x01name\x00{appInfo.Name}\x00", startIndex); //Alternative2
if (startOfDataArea > 0)
{
startIndex = startOfDataArea + 10;
int nextLaunch = -1;
do
{
var executable = _appInfoText.IndexOf($"\x00\x01executable\x00", startOfDataArea);
if (executable>-1 && nextLaunch == -1)
{
nextLaunch = _appInfoText.IndexOf($"\x00\x01launch\x00", executable);
}
if ((nextLaunch <= 0 || executable < nextLaunch) && executable > 0)
{
if (executable > 0)
{
executable += 10;
string filename = "";
while (_appInfoText[executable] != '\x00')
{
filename += _appInfoText[executable];
executable++;
}
if (filename.Contains("://"))
{
//EA or other external
return filename; //Need to use other means to grab the EXE here.
}
fullName = Path.Combine(appInfo.GameRoot, filename);
startOfDataArea = executable + 1;
startIndex = startOfDataArea + 10;
}
}
else
{
break;
}
}
while (!File.Exists(fullName) && maxTries-- > 0);
}
else
{
return null;
}
} while (!File.Exists(fullName) && maxTries-- > 0);
if (File.Exists(fullName)) return fullName;
return null;
}
static List<string> GetSteamLibs()
{
var steamPath = GetSteamPath();
var libraries = new List<string>() { steamPath };
var listFile = Path.Combine(steamPath, #"steamapps\libraryfolders.vdf");
var lines = File.ReadAllLines(listFile);
foreach (var line in lines)
{
var match = Regex.Match(line, #"""(?<path>\w:\\\\.*)""");
if (match.Success)
{
var path = match.Groups["path"].Value.Replace(#"\\", #"\");
if (Directory.Exists(path))
{
libraries.Add(path);
}
}
}
return libraries;
}
static string GetSteamPath()
{
return #"C:\Spill\Steam";
}
class AppInfo
{
public string Id { get; internal set; }
public string Name { get; internal set; }
public string SteamUrl { get; internal set; }
public string Manifest { get; internal set; }
public string GameRoot { get; internal set; }
public string Executable { get; internal set; }
public string InstallDir { get; internal set; }
public override string ToString()
{
return $"{Name} ({Id}) - {SteamUrl} - {Executable}";
}
}
}
}
I have a Modbus TCP/IP to MODBUS RTU converter , which comes with a default IP of 192.168.0.1 . I need to develop a small c# Winform app to change this device's IP address to any desired IP address. How do I do that?.
You could do it with WMI (Windows Management Instrumentation).
First, you have to add the reference for System.Management to your Project.
Second, you need to find the NetworkInterface for your network connection by name:
using System.Net.NetworkInformation;
using System.Management;
public class NetworkManager
{
public static NetworkInterface GetNetworkInterface(string sName)
{
NetworkInterface NetInterface = null;
// Precondition
if (sName == "") return null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
if (ni.Name == sName)
{
NetInterface = ni;
break;
}
}
return NetInterface;
}
Third, you have to create a ManagementObject for your NetworkInterface:
public static ManagementObject GetNetworkAdapterManagementObject(NetworkInterface NetInterface)
{
ManagementObject oMngObj = null;
// Precondition
if (NetInterface == null) return null;
string sNI = NetInterface.Id;
ManagementClass oMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection oMOC = oMC.GetInstances();
foreach (ManagementObject oMO in oMOC)
{
string sMO = oMO["SettingID"].ToString();
if (sMO == sNI)
{
// Found
oMngObj = oMO;
break;
}
}
return oMngObj;
}
Fours, you can set the ipadress with:
public static bool SetIPAdress(ManagementObject oMO, string[] saIPAdress, string[] saSubnetMask)
{
bool bErg = false;
try
{
// Precondition
if (oMO == null) return false;
if (saIPAdress == null) return false;
if (saSubnetMask == null) return false;
// Get ManagementBaseObject
ManagementBaseObject oNewIP = null;
oNewIP = oMO.GetMethodParameters("EnableStatic");
oNewIP["IPAddress"] = saIPAdress;
oNewIP["SubnetMask"] = saSubnetMask;
// Invoke
oMO.InvokeMethod("EnableStatic", oNewIP, null);
// Alles ok
bErg = true;
}
catch (Exception ex)
{
Console.WriteLine("SetIPAdress failed: " + ex.Message);
}
return bErg;
}
}
Now you can use it, for example in a button click event handler:
private void button1_Click(object sender, EventArgs e)
{
string sConn = "LAN-Verbindung";
NetworkInterface oNI = NetworkManager.GetNetworkInterface(sConn);
ManagementObject oMO = NetworkManager.GetNetworkAdapterManagementObject(oNI);
string sIPAdress = "192.168.1.1";
string sSubnetMask = "255.255.255.0";
string[] saIPAdress = {sIPAdress};
string[] saSubnetMask = {sSubnetMask};
if (NetworkManager.SetIPAdress(oMO, saIPAdress, saSubnetMask))
{
Console.WriteLine("Yes...");
}
}
Depending on the policies on your pc, may be you have to run the program as Administrator...
I want to free a TCP port during startup of my application (asking confirmation to user), how to get the PID number and then, if the user confirm, kill it?
I know I can get this information by netstat, but how to do it in a script or better in a C# method.
You can run netstat then redirect the output to a text stream so you can parse and get the info you want.
Here is what i did.
Run netstat -a -n -o as a Process
redirect the standard out put and capture the output text
capture the result, parse and return all the processes in use
check if the port is being used
find the process using linq
Run Process.Kill()
you will have to do the exception handling.
namespace test
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Console.WriteLine("Port number you want to clear");
var input = Console.ReadLine();
//var port = int.Parse(input);
var prc = new ProcManager();
prc.KillByPort(7972); //prc.KillbyPort(port);
}
}
public class PRC
{
public int PID { get; set; }
public int Port { get; set; }
public string Protocol { get; set; }
}
public class ProcManager
{
public void KillByPort(int port)
{
var processes = GetAllProcesses();
if (processes.Any(p => p.Port == port))
try{
Process.GetProcessById(processes.First(p => p.Port == port).PID).Kill();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
else
{
Console.WriteLine("No process to kill!");
}
}
public List<PRC> GetAllProcesses()
{
var pStartInfo = new ProcessStartInfo();
pStartInfo.FileName = "netstat.exe";
pStartInfo.Arguments = "-a -n -o";
pStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
pStartInfo.UseShellExecute = false;
pStartInfo.RedirectStandardInput = true;
pStartInfo.RedirectStandardOutput = true;
pStartInfo.RedirectStandardError = true;
var process = new Process()
{
StartInfo = pStartInfo
};
process.Start();
var soStream = process.StandardOutput;
var output = soStream.ReadToEnd();
if(process.ExitCode != 0)
throw new Exception("somethign broke");
var result = new List<PRC>();
var lines = Regex.Split(output, "\r\n");
foreach (var line in lines)
{
if(line.Trim().StartsWith("Proto"))
continue;
var parts = line.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
var len = parts.Length;
if(len > 2)
result.Add(new PRC
{
Protocol = parts[0],
Port = int.Parse(parts[1].Split(':').Last()),
PID = int.Parse(parts[len - 1])
});
}
return result;
}
}
}
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.
I have been designing a program using Visual C# and have came across an issue with making my program interact with web browsers. Basically what I need is to retrieve the URL address from a web browser (Internet Explorer, Firefox, Chrome etc...).
I figured this wouldn't be too difficult of a task, but after days and days of research and tests, it seems almost impossible! Thus far, I have come across this...
Get Firefox URL?
Which has the code below:
using NDde.Client;
Class Test
{
public static string GetFirefoxURL()
{
DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo");
dde.Connect();
string url = dde.Request("URL", int.MaxValue);
dde.Disconnect();
return url;
}
}
Which is perfect for Firefox, but for some reason I cannot get it to work with anything else. I have changed the portion of the code that says "Firefox" to "Iexplore" like I found all over the internet, along with trying other forms of expressing Internet Explorer, and I get the following error:
"Client failed to connect to "IExplorer|WWW_GetWindowInfo", Make sure the server application is running and that it supports the specified service name and topic name pair"
Any help on the issue would be much appreciated as it has become quite a task to figure out.
Here is a code based on Microsoft UI Automation:
public static string GetChromeUrl(Process process)
{
if (process == null)
throw new ArgumentNullException("process");
if (process.MainWindowHandle == IntPtr.Zero)
return null;
AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
if (element == null)
return null;
AutomationElement edit = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
}
public static string GetInternetExplorerUrl(Process process)
{
if (process == null)
throw new ArgumentNullException("process");
if (process.MainWindowHandle == IntPtr.Zero)
return null;
AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
if (element == null)
return null;
AutomationElement rebar = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "ReBarWindow32"));
if (rebar == null)
return null;
AutomationElement edit = rebar.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
}
public static string GetFirefoxUrl(Process process)
{
if (process == null)
throw new ArgumentNullException("process");
if (process.MainWindowHandle == IntPtr.Zero)
return null;
AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
if (element == null)
return null;
AutomationElement doc = element.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document));
if (doc == null)
return null;
return ((ValuePattern)doc.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
}
You can use the UI Spy tool to understand the visual hierarchy for all 3 browsers. You may need to adapt things to make sure it really work in your specific cases, but you should get the general idea with these samples.
And an example that dumps all urls for all the 3 types of process (IE, FF, CH) currently running in the system:
static void Main(string[] args)
{
foreach (Process process in Process.GetProcessesByName("firefox"))
{
string url = GetFirefoxUrl(process);
if (url == null)
continue;
Console.WriteLine("FF Url for '" + process.MainWindowTitle + "' is " + url);
}
foreach (Process process in Process.GetProcessesByName("iexplore"))
{
string url = GetInternetExplorerUrl(process);
if (url == null)
continue;
Console.WriteLine("IE Url for '" + process.MainWindowTitle + "' is " + url);
}
foreach (Process process in Process.GetProcessesByName("chrome"))
{
string url = GetChromeUrl(process);
if (url == null)
continue;
Console.WriteLine("CH Url for '" + process.MainWindowTitle + "' is " + url);
}
}
Mourier, thank you for your solution Microsoft UI Automation.
Even so it didn't worked for Firefox 41.0,
I analysed the Firefox window structure with the little tool "Automation Spy".
Then I've changed the search conditions slightly, and it worked perfectly!
public static string GetFirefoxUrl(Process process)
{
if (process == null)
throw new ArgumentNullException("process");
if (process.MainWindowHandle == IntPtr.Zero)
return null;
AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
if (element == null)
return null;
element = element.FindFirst(TreeScope.Subtree,
new AndCondition(
new PropertyCondition(AutomationElement.NameProperty, "search or enter address", PropertyConditionFlags.IgnoreCase),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)));
if (element == null)
return null;
return ((ValuePattern)element.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
}
And here is the solution for Chromium 48:
public static string GetChromeUrl(Process process)
{
if (process == null)
throw new ArgumentNullException("process");
if (process.MainWindowHandle == IntPtr.Zero)
return null;
AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
if (element == null)
return null;
AutomationElement edit = element.FindFirst(TreeScope.Subtree,
new AndCondition(
new PropertyCondition(AutomationElement.NameProperty, "address and search bar", PropertyConditionFlags.IgnoreCase),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)));
return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
}
Automation Spy shows Firefox window controls structure. The control of type 'edit' with the name 'Search or enter address' holds the url:
Note: In your .NET project you need 2 references:
UIAutomationClient.dll
UIAutomationTypes.dll
Use parameter "1" instead of "URL" in oDde.Request("URL", int.MaxValue) for IE.
public static void ProcessIEURLs()
{
string sURL;
try
{
DdeClient oDde = new DdeClient("IExplore", "WWW_GetWindowInfo");
try
{
oDde.Connect();
sURL = oDde.Request("1", int.MaxValue);
oDde.Disconnect();
bool bVisited = false;
if ( oVisitedURLList != null && oVisitedURLList.Count > 0 )
{
bVisited = FindURL(sURL, oVisitedURLList);
}
if ( !bVisited )
{
oVisitedURLList.Add(sURL);
}
}
catch ( Exception ex )
{
throw ex;
}
}
catch ( Exception ex )
{
throw ex;
}
}
Here's what I have so far (though Chrome I'm not finding any helpful articles on, other than using FindWindowEx (I don't particularly like that method, personally).
public class BrowserLocation
{
/// <summary>
/// Structure to hold the details regarding a browed location
/// </summary>
public struct URLDetails
{
/// <summary>
/// URL (location)
/// </summary>
public String URL;
/// <summary>
/// Document title
/// </summary>
public String Title;
}
#region Internet Explorer
// requires the following DLL added as a reference:
// C:\Windows\System32\shdocvw.dll
/// <summary>
/// Retrieve the current open URLs in Internet Explorer
/// </summary>
/// <returns></returns>
public static URLDetails[] InternetExplorer()
{
System.Collections.Generic.List<URLDetails> URLs = new System.Collections.Generic.List<URLDetails>();
var shellWindows = new SHDocVw.ShellWindows();
foreach (SHDocVw.InternetExplorer ie in shellWindows)
URLs.Add(new URLDetails() { URL = ie.LocationURL, Title = ie.LocationName });
return URLs.ToArray();
}
#endregion
#region Firefox
// This requires NDde
// http://ndde.codeplex.com/
public static URLDetails[] Firefox()
{
NDde.Client.DdeClient dde = new NDde.Client.DdeClient("Firefox", "WWW_GetWindowInfo");
try
{
dde.Connect();
String url = dde.Request("URL", Int32.MaxValue);
dde.Disconnect();
Int32 stop = url.IndexOf('"', 1);
return new URLDetails[]{
new URLDetails()
{
URL = url.Substring(1, stop - 1),
Title = url.Substring(stop + 3, url.Length - stop - 8)
}
};
}
catch (Exception)
{
return null;
}
}
#endregion
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Internet Explorer: ");
(new List<BrowserLocation.URLDetails>(BrowserLocation.InternetExplorer())).ForEach(u =>
{
Console.WriteLine("[{0}]\r\n{1}\r\n", u.Title, u.URL);
});
Console.WriteLine();
Console.WriteLine("Firefox:");
(new List<BrowserLocation.URLDetails>(BrowserLocation.Firefox())).ForEach(u =>
{
Console.WriteLine("[{0}]\r\n{1}\r\n", u.Title, u.URL);
});
Console.WriteLine();
}
}
WWW_GetWindowInfo is supported in IE and has been since version 3.02 back in the 16 bit days! Works for Firefox and Opera
I believe that Chrome is in fact the odd one out.
I've got no knowledge of how things are beyond those four.
the bese choice is to use selenium webdriver. best and power full api with full premision