Registry R/W in C#


C# has a nice wrap for registry manipulations.

The usage of the registry under C# is fairlyeasy, and opens the world of the registry for your application to usefor reading and/or writing.

For our example, lets not use any reg key thatis important, so that we will not (by accident of course) spoilanything in there.

Open regedit.exe and navigate to HKEY_LOCAL_MACHINE\software and create your own sub-key there, call it "MyTestRegKey"

Create 2 string values inside this key, nameone "Name" and one "Password", and assign them the string values -"Guest", "123456" respectively.

Now you should have 2 values at location: "HKEY_LOCAL_MACHINE\software\MyTestRegKey\".

So lets create a function which reads them.

using Microsoft.Win32;

public void ReadMyTestRegKey()

{

RegistryKey regkey;/* new Microsoft.Win32 Registry Key */

regkey = Registry.LocalMachine.OpenSubKey(@"Software\MyTestRegKey");

string[] valnames = regkey.GetValueNames();

string val0 = (string)regkey.GetValue(valnames[0]);

string val1 = (string)regkey.GetValue(valnames[1]);

}

Very easy and clean.

The OpenSubKey method returns a Registry Keythat is Locked for changes, so if we mean in our function to edit thekey as well, we should use the overloaded OpenSubKey which takes notonly the registry key, but a bool variable who states if we want to beable to edit whats in there.

A different method called CreateSubKey hasonly one form, which takes a registry location, the difference withOpenSubKey is that if the KEY in the registry does not exist it iscreated, while OpenSubKey return null if the key was not found.

on the key that has returned, you can set new values, open new sub keys, and to them new values and sub keys and so on:

public void ReadMyTestRegKey()

{

RegistryKey regkey;/* new Microsoft.Win32 Registry Key */

regkey = Registry.LocalMachine.CreateSubKey(@"Software\MyTestRegKey");

/*regkey = Registry.LocalMachine.OpenSubKey(@"Software\MyTestRegKey");*/

string[] valnames = regkey.GetValueNames();

string val0 = (string)regkey.GetValue(valnames[0]);

string val1 = (string)regkey.GetValue(valnames[1]);

regkey.SetValue("Domain",(string)"Workgroup");

Registry.LocalMachine.Flush();

}

I have commented out the first method we used,and added the CreateSubKey method instead, because the Key exist, theket is opened and returned, and after that we Set a value to a newstring value that does not exist, so it is being created for us. if thevalue "Domain" existed, with another value for exaple, then at the callto SetValue the value of Domain would have chnage to reflect the newstring.

Very important to note the Flush() method,which is not necessary to call to, registry chnages are auto saved, byinterval stated by the system, while system shutdown, the MSDN say: "ingeneral, Flush rarely, if ever, need to be used".

Most Commented Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!