Introduction
Well, apparently the registry seems to have lost some of its importance with the arrival of .NET, at least that's the
impression I seem to get. But luckily for us, Microsoft has given us two nice classes for doing just about anything we want to do
with the registry. The classes are Microsoft.Win32.RegistryKey
and Microsoft.Win32.Registry
. They have
both been put into the Microsoft.Win32
namespace as you can see because the registry is totally Microsoft Win32
specific. Without too much fuss, let's get into business and try and do some of the stuff we normally do with the registry.
Reading the registry
RegistryKey rkey = Registry.LocalMachine;
RegistryKey rkey1=rkey.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
listBox1.Items.Add("RegisteredOwner :- " +
rkey1.GetValue("RegisteredOwner"));
listBox1.Items.Add("RegisteredOrganization :- " +
rkey1.GetValue("RegisteredOrganization"));
listBox1.Items.Add("ProductName :- " +
rkey1.GetValue("ProductName"));
listBox1.Items.Add("CSDVersion :- " +
rkey1.GetValue("CSDVersion"));
listBox1.Items.Add("SystemRoot :- " +
rkey1.GetValue("SystemRoot"));
rkey1.Close();
Writing to the registry
rkey = Registry.CurrentUser;
rkey1 = rkey.OpenSubKey("Software",true);
RegistryKey rkey2 = rkey1.CreateSubKey("Tweety");
rkey2.SetValue("Name","Tweety");
rkey2.SetValue("Age",24);
rkey2.Close();
rkey1.Close();
If you open regedit, you'll see that the new key has been added and the values have indeed been written correctly.
Enumeration
Okay, we've read from and written into the registry. Now let's enumerate some values.
rkey1 = rkey.OpenSubKey("Software\\Microsoft\\" +
"Internet Account Manager\\Accounts\\00000001");
string[] s_arr = rkey1.GetValueNames();
foreach(String s in s_arr)
{
listBox1.Items.Add(s + " :- " + rkey1.GetValue(s));
}
rkey1.Close();
Well, that's about it I guess. This was originally written as part of an internal tutorial. I didn't modify it too much except
for taking better screenshots.
Thanks.
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.
Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.
Nish's Technology Blog :
voidnish.wordpress.com