Thursday, October 11, 2007

LINQ to Registry

The following example pulls all the values out of the registry in the "Uninstall" section (what shows up in the Add/Remove programs control panel applet).

I created a little class that gets instantiated during the LINQ query, used to just hold values for display in a grid.

class InstalledApp
{
    public InstalledApp(RegistryKey uninstallKey, string keyName)
    {
        RegistryKey key = uninstallKey.OpenSubKey(keyName, false);
 
        try
        {
            var d = key.GetValue("DisplayName");
            if (d != null) DisplayName = d.ToString();
 
            var s = key.GetValue("UninstallString");
            if (s != null) UnInstallPath = s.ToString();
 
        }
        finally
        {
            key.Close();
        }
 
 
    }
    public string DisplayName { get; set; }
    public string UnInstallPath { get; set; }
}

Next we pull all of the registry values out for the installed apps, then open up all the sub keys and read out the display name and the uninstall paths.

      RegistryKey lm_run = Registry.LocalMachine.OpenSubKey(
@"Software\Microsoft\Windows\CurrentVersion\Uninstall", false);
      try
      {
          bindingSource.DataSource = (from name in lm_run.GetSubKeyNames()
                                      let app = new InstalledApp(lm_run, name)
                                      where app.DisplayName != null
                                      select app).ToList();
      }
      finally
      {
          lm_run.Close();
      }


Assuming "bindingSource" is of type BindingSource and is the datasource for a grid, this code will populate the grid with a the apps' display names that can be uninstalled and the command to do it.

No comments: