Wednesday, July 7, 2010

Create a key in the registry using C#

Introduction

Microsoft.win32 Namespace is containing register class; Register class is used to manipulate the system registry. It represents a Key level node in the windows registry.

The registry acts as information for the operating system and application on a computer. Register keys are the base unit of registry. Each key have multiple values alone with it.

C# Code for creates a key in the register.

CreateSubKey method to creates a new subkey or opens an existing subkey for write access


Example:
Microsoft.Win32.RegistryKey mykey;
mykey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(“Muhil Software”);

To set a value for the particular key is setValue method

Example:

mykey.SetValue(“Muhil”, “12345789”);


Some time exceptions will occur due to the name of the key is null or the user does not have permissions to create registry key or they key name exceeds the limit or if the key is closed or the register key is read only.


More secure to write data into register use Microsoft.Win32.Registry.CurrentUser instead of Microsoft.Win32.Registry.LocalMachine.
Complete listing for create a key.

Microsoft.Win32.RegistryKey mykey;
mykey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(“Muhil Software”);
mykey.SetValue(“Muhil”, “12345789”);
mykey.close();


Retrieve Registry key information.

RegistryKey.GetValue Method retrieves the value in a specified name. If returns null the name does not exist in the registry and it will return as a object.
Example:

key.GetValue(“Muhil”);

Complete listing to retrieve the registry key

Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Muhil Software");
String s = (String)key.GetValue("Muhil");

OpenSubKey method is used to open the register under {HKEY_CURRENT_USER\Muhil Software}. GetValue method return the object associated with name.

No comments:

Post a Comment