C # provides two primary registry-related classes:
RegistryAndRegistryKey,These two classes belongMicrosoft. Win32Namespace
The Registry class contains five public static fields, representing the five basic primary keys respectively:
Registry. ClassesRoot
Registry. CurrentUser
Registry. LocalMachine
Registry. Users
Registry. Current Config
These five classes correspond to the five pre-defined primary keys in the second-level directory of the Registry respectively.
RegistryKey class provides methods for registry operations
CreateSubKey // create a subkey
OpenSubKey // open a subkey
DeleteKey // delete a subkey
DeleteKeyTree // delete a key and all its keys
GetValue // obtain the key value
SetValue // set the key value
Example of creating a child key and setting a key value:
Code
private void WTRegedit(string name,string tovalue)
{
RegistryKey hklm = Registry.LocalMachine;
RegistryKey software = hklm.OpenSubKey("SOFTWARE",true);
RegistryKey aimdir = software.CreateSubKey("XXX");
aimdir.SetValue(name,tovalue);
}
Example of deleting a key value:
Code
private void DeleteRegist(string name)
{
string[] aimnames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey("SOFTWARE",true);
aimnames = software.GetSubKeyNames();
foreach(string aimKey in aimnames)
{
if(aimKey == name)
aimdir.DeleteSubKeyTree(name);
}
}
When it comes to deleting a key value, you must pay attention to another issue: system permissions! Deleting a key directly triggers an unauthorized operation.
This involves another class.RegistrySecurity, It belongsSystem. Security. AccessControlNamespace
RegistrySecurityThe object specifies the access permission for the registry key and how to audit access attempts. The access permission for the registry key is embodied in rules, each access rule is composed of oneRegistryAccessRuleObject Representation. Each audit rule is composed of oneRegistryAuditRuleObject Representation
To copy access control security from one registry key to another, useRegistryKey. GetAccessControlMethodRegistrySecurityObject, and then useRegistryKey. SetAccessControlMethod or an acceptanceRegistrySecurityThe constructor of the object specifies the rule to the second registry key.
Sample Code:
Code
RegistrySecurity rsy = new Registr