How to write and read from Registry in C#?

Local data storage in client machine developer use registry.this store small data like application settings.It can modify manually to edit in regedit. In this post we learn about read and write in registry.Registry is one structure of data by link or keys and sub keys.

How to write and read from Registry in C#?

For write in registry need to create key or path where want to write.so if we have key then open it and not then create it.

RegistryKey Newkey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\NewKey");

Registry.CurrentUser => "\HKEY_CURRENT_USER\"
@"SOFTWARE\KeyName" => this key is located on "HKEY_CURRENT_USER\Software\NewKey"
CreateSubKey() => create new key

RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Key",true);

OpenSubKey() => opne allready exist Key
OpenSubKey(@"SOFTWARE\Key",true) => OPen "HKEY_CURRENT_USER\SOFTWARE\Key" and second parameter "True" is allow write keys otherwise not permit to write only can read keys.

Set or insert or edit key data 

Key.SetValue("Setting1", "Setting1Value");

Key.SetValue("Keyname","KeyValue"); => setvalue() set key value under open or create Key.first parameter is keyname what we want.and second is KeyValue this value that want to set.

Get Key data
Key.GetValue("Setting1").ToString();

Key.GetValue("Keyname").ToString(); => GetValue() get key value under open key.parameter is key name which key data want to get.That can store in variable.and can operation on it.

After get and set close the Key.by Key.Close() function.

Check this example for better understanding

RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Key",true);
//Open key with write mode
if (Key != null)//check key is exist or not null
{
if (Key.GetValue("Setting1") == null)//check Key exist
{
string Setting1=Key.GetValue("Setting1").ToString();
//get value of Setting1 Key
Key.SetValue("Setting1", "Setting1 New Value");
//Set new value of setting1 Key
}
}
else
{
//if Key not foun create Key for set value
RegistryKey Newkey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Key");
//Create Key for set value
Newkey.SetValue("Setting1", "Setting1 New Value");
//Set value in key Setting1
Newkey.Close();
//close Key
}
Key.Close();

You can check this to open registry in your computer.for check open RUN and write regedit.
Explore : HKEY_CURRENT_USER => SOFTWARE => Key
You find Setting1 Key and on double click find value of key -> "Setting1 New Value".try your self and say if any problem in it.

This code is usefull for save local settings.licence verification,check user update in local system.

See also this post

How to get html of web page in string by web page url

How to resolve "Logon Failed" Error in crystal report

Comments

Popular posts from this blog

Populate combo box for month and year in c#

How to get month days count from date or month and year

CRUD Operations in win form application with access database