Saving objects to the registry

by OfirYaron 4/27/2009 7:49:00 AM

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;

}

}

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Related posts

Comments

4/27/2009 10:45:34 PM

Thanks!

Mark

Comments are closed

Powered by BlogEngine.NET 1.3.0.0
Theme by Mads Kristensen

About the author

Name of author Author name
Something about me and what I do.

E-mail me Send mail

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent posts

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Sign in