Using the registry in .NET

by Mikael Henriksson 27. January 2009 18:59

Today I learned something new and I kind of like it so I thought I'd share my expertise! :)

We have four instances of the same application running on the same machine but all with different configurations (all are executed from thin clients via RDP). Now that's nothing new, nothing strange it's just the way it is. I need to add another thin client and the new one need to need to share some configuration with one of the others. They both need to have full control over our packages configuration. Never mind what types of packages since that is utterly unimportant. I was looking at reading / writing external config files but realized I'd just get lost somewhere. That is why I decided to have a look at the registry!

First I need to create something to "hold" my registry data to make it reusable throughout my application. Oh you could indeed have it all stored in a config file but I'd like to minimize the risk of someone changing / deleting the file by mistake. And since this registry class isnt subject of change for a long time I chose this approach instead but feel free to pick your own choice.

using Microsoft.Win32;
namespace Company.Application.RegistryConfiguration
{
    public class RegistryKeys
    {
        public static RegistryKey PackageSettings()
        {
            RegistryKey keyPS = Registry.LocalMachine
                .CreateSubKey("Software")
                .CreateSubKey("Company\\Package Settings"); return keyPS;
        }
    } 
    public class RegistryValues
    {
        public const string ValueQuantityInHistory = "QuantityInHistory";
        public const string ValueQuantityInDatabase = "QuantityInDataBase";
        public const string ValuePackageNumber = "PackageNumber";
        public const string ValueMinPackageNumber = "MinPackageNumber";
        public const string ValueMaxPackageNumber = "MaxPackageNumber";
    }
}

Next thing is reading and writing to the registry based on my 2 Registry Classes. It's all a walk in the park really. From here on it's even more straight forward, I'll just let you have a look at the full Packages class. Don't forget to reference Microsoft.Win32 with a simple using.

public class Packages    
{        
	private RegistryKey keyPS = RegistryKeys.PackageSettings();         
	private int _quantityInDb;        
	private int _quantityInHistory;         
	private int _packageNr;        
	private int _minPackageNr;        
	private int _maxPackageNr;     

	/// <summary>        
	/// Loads the package configuration from the registry        
	/// </summary>       
	/// <remarks>       
	/// Checks for null values, if we have a null value something messed up and we load the config from backup file       
	/// </remarks>        
	private void LoadPackageSettings()        
	{             
		_quantityInDb = Convert.ToInt32(keyPS.GetValue(RegistryValues.ValueQuantityInDatabase));           
		_quantityInHistory = Convert.ToInt32(keyPS.GetValue(RegistryValues.ValueQuantityInHistory));            
		_packageNr = Convert.ToInt32(keyPS.GetValue(RegistryValues.ValuePackageNumber));            
		_minPackageNr = Convert.ToInt32(keyPS.GetValue(RegistryValues.ValueMinPackageNumber));            
		_maxPackageNr = Convert.ToInt32(keyPS.GetValue(RegistryValues.ValueMaxPackageNumber));             
		
		if (_quantityInDb.Equals(0) && _quantityInHistory.Equals(0) && _minPackageNr.Equals(0))            
		{                
			LoadBackedUpPackageSettings();            
		}         
	}         
	
	/// <summary>
	/// Saves the package configuration in the registry       
	/// </summary>        
	/// <remarks>        
	/// Lastly we backup all settings to let's say a text file.        
	/// </remarks>        
	private void SavePackageSettings()        
	{            
		try
		{
			keyPS.SetValue(RegistryValues.ValueQuantityInDatabase, _quantityInDb, RegistryValueKind.DWord);                
			keyPS.SetValue(RegistryValues.ValueQuantityInHistory, _quantityInHistory, RegistryValueKind.DWord);                 
			keyPS.SetValue(RegistryValues.ValuePackageNumber, _packageNr, RegistryValueKind.DWord);                
			keyPS.SetValue(RegistryValues.ValueMinPackageNumber, _minPackageNr, RegistryValueKind.DWord);                
			keyPS.SetValue(RegistryValues.ValueMaxPackageNumber, _maxPackageNr, RegistryValueKind.DWord);
		}            
		catch (Exception ex)            
		{                
			// Logger.LogException(ex);                
			// Tell the user something went wrong            
		}            
		finally
		{
			BackupPackageSettings();
		}       
	}    
}

There are several more ways to use the registry, this is just one of them, maybe not even a good way. Don't look at me, I'm not an expert! Now go hack that registry of yours :)

Tags: ,

C# | Windows Forms

blog comments powered by Disqus