Thursday, June 2, 2011

How to Read and Write on Registry using C#

In some cases it is necessary to work with the Registry. The .NET Framework provides some classes for this. This example shows you, how to worky easily with the registry.



Namespace : Microsoft.Win32



Write Information to the Registry



RegistryKey rk = Registry.CurrentUser;
RegistryKey rkSoftware = rk.OpenSubKey("Software", true);
if (rkSoftware != null)
{
RegistryKey rkCompany = rkSoftware.OpenSubKey("Company Name",true);
if (rkCompany == null)
{
rkCompany = rkSoftware.CreateSubKey("\"Company Name");
}
RegistryKey rkInstaller = rkCompany.OpenSubKey("MySoftware", true);
if (rkInstaller == null)
rkInstaller = rkCompany.CreateSubKey("MySoftware");

rkInstaller.SetValue("value1", "test1");
rkInstaller.SetValue("value2", "test2");

rkInstaller.Close();
rkCompany.Close();
rkSoftware.Close();
}
rk.Close();



Read Information from the registry



RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"SoftwareCompany NameMySoftware");
if (rk != null)
{
string value1 = (string)rk.GetValue("value1");
string value2 = (string)rk.GetValue("value2");

rk.Close();
}

No comments:

Post a Comment