C# Edit Registry Keys or Values

First

Before starting to edit registry values/keys, include in your project’s source this namespace Microsoft.Win32. It will give you access to the required Registry functions.

So, make sure you add this:

1

usingMicrosoft.Win32;

In order to edit anything, you must:

open the key where you want to edit (set a path)

add/delete/edit what you want

close the key

Note: in this tutorial I used Windows’ startup Key (path), but you can use anything you want.

So your snippet will look like this:

1
2
3
4
5
6
7
8
9

//this is how your key will look like
//the 2nd argument (true) is indicating that the key is writable
RegistryKeykey=Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run",true);//here you put the code to edit/delete values or subkeys
//which are found in: 'Software\Microsoft\Windows\CurrentVersion\Run'
//and finally, you close the key
key.Close();

Creating a Key

A key is a subfolder, in which you can add multiple values.
To create a key:

1
2
3
4
5
6

RegistryKeykey=Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run",true);//create a new key
key.CreateSubKey("someKey");key.Close();

Deleting a Key

In order to delete a key, you have to do the same thing: set the path then simply delete it.

Reading a value

You can get a value from a key by knowing its name:

1
2
3
4
5
6

RegistryKeykey=Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\someKey",true);//getting the value
stringdata=key.GetValue("someValue").ToString();//returns the text found in 'someValue'
key.Close();