28

As suggested here, I need to iterate through entries in

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\

to find out the installed path of my application. How to iterate so that I can find out the InstallLocation value given the DisplayName. How to do it efficiently in C#.

Community
  • 1
  • 1
Nemo
  • 4,601
  • 11
  • 43
  • 46
  • 2
    Be aware that to access HKEY_LOCAL_MACHINE your application must have administrator privileges (for all OS after XP). I wonder if the question should be 'how to find the installed path of my application'? If the scenario is for upgrades etc. I'm thinking that common application data may be a better go. – Rob Smyth Nov 03 '12 at 10:25

2 Answers2

42

Below is code to achieve your goal:

using Microsoft.Win32;
class Program
{
    static void Main(string[] args)
    {
        RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
        foreach (var v in key.GetSubKeyNames())
        {
            Console.WriteLine(v);

            RegistryKey productKey = key.OpenSubKey(v);
            if (productKey != null)
            {
                foreach (var value in productKey.GetValueNames())
                {
                    Console.WriteLine("\tValue:" + value);

                    // Check for the publisher to ensure it's our product
                    string keyValue = Convert.ToString(productKey.GetValue("Publisher"));
                    if (!keyValue.Equals("MyPublisherCompanyName", StringComparison.OrdinalIgnoreCase))
                        continue;

                    string productName = Convert.ToString(productKey.GetValue("DisplayName"));
                    if (!productName.Equals("MyProductName", StringComparison.OrdinalIgnoreCase))
                        return;

                    string uninstallPath = Convert.ToString(productKey.GetValue("InstallSource"));

                    // Do something with this valuable information
                }
            }
        }

        Console.ReadLine();
    }
}

Edit: See this method for a more comprehensive way to find an Applications Install Path, it demonstrates the using disposing as suggested in the comments. https://stackoverflow.com/a/26686738/495455

Noah Cristino
  • 757
  • 8
  • 29
Mike J
  • 3,049
  • 22
  • 21
2
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Whater\The\Key"))
{
  if (key != null)
  {
    foreach (string ValueOfName in key.GetValueNames())
    {
      try
      {
         bool Value = bool.Parse((string)key.GetValue(ValueOfName));
      }
      catch (Exception ex) {}
    }
 }
}

With a bool cast :D - so the string is expected to be True or False.

For the user registry hive use Registry.CurrentUser instead of Registry.LocalMachine

rémy
  • 1,026
  • 13
  • 18