How to create a key in the registry using C#?

Posted by in Windows Forms category on for Beginner level | Views : 43430 red flag
Rating: 5 out of 5  
 4 vote(s)

In this article, I will be explain How to create a key in the registry using C#?


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

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

It will create a subkey under the current User(HKEY_USERS) like below screen (see image attached)


To set a value for the particular key is setValue method


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”);

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.



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.

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Muhil an
Member Level:
Member Status: Member
Member Since: 11/30/2009 2:46:25 AM
Country: India

working as an IT System Analyst,tmuhilan at gmail com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)