I've needed a way to save a complex object to the registry so I've wrote this class,
basically it uses reflection in order to find the properties of a generic type that was given and fill them in with the matching (by name) key on the registry.
public class RegistrySmartAgent
{
public string BasePath { get; private set; }public RegistrySmartAgent(string basePath)
{
BasePath = basePath;
}
private T ReadSingle<T>(string fullPath) where T : new()
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(fullPath);
T t = new T();
foreach (string name in key.GetValueNames())
{
Type typeInfo = typeof(T);
PropertyInfo propertyInfo = typeInfo.GetProperty(name);
if ((propertyInfo != null) &&
(propertyInfo.PropertyType == typeof(int)) ||(propertyInfo.PropertyType ==
typeof(string)) ||
(propertyInfo.PropertyType == typeof(double)))propertyInfo.SetValue(t, key.GetValue(name),
null);
}
return t;
}
public IDictionary<string, T> Read<T>(string subName) where T : new()
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(BasePath + "\\" + subName);
IDictionary<string,T> retList = new Dictionary<string,T>();
foreach (string name in key.GetSubKeyNames())
{
retList.Add(name,ReadSingle<T>(BasePath + "\\" + subName + "\\" + name));
}
return retList;
}
public bool Write<T>(string subName, T element)
{
Type typeInfo = typeof(T);
PropertyInfo[] properties = typeInfo.GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(BasePath + "\\" + subName);
if (key==null)key =
Registry.LocalMachine.CreateSubKey(BasePath + "\\" + subName);key.SetValue(propertyInfo.Name, propertyInfo.GetValue(element, null));
}
return true;
}
}