Wednesday, August 26, 2009

Read or Write on Registry in C#

Registry is a special place where applications stores its setting. Although Isolated storage for .net is a preferred way for storing
application settings yet registry has its own benefit. Normally it is difficult to find application created registry entries(if created carefully).
Below is a sample C# code.

//It will create a new subkey if not already created. otherwise it opens the existing one with write access.
RegistryKey objRegistryKey = Registry.CurrentUser.CreateSubKey("App_Name");
//Suppose i want to save last open time when application opened.
objRegistryKey.SetValue("LastOpenTime", DateTime.Now.ToString());

To get the value from registry, you use
string lastOpenDT = objRegistryKey.GetValue("LastOpenTime") as string;

The GetValue return the object type. you can than cast to the appropriate type.

Don't forget to add Microsoft.Win32 namespace.

For further reading,you can see the following two classess at msdn.
Registry,RegistryKey class.