Detailed Explanation of C Operation Registry Method

  • 2021-08-31 08:50:54
  • OfStack

This article illustrates how C # manipulates the registry. Share it for your reference, as follows:

Below, we will use the managed language C # registry operation under NET. The main contents include: the creation, opening and deletion of registry keys, the creation (setting value, modification), reading and deletion of key values, and judging whether registry keys exist and whether key values exist.

Preparations:

1. To manipulate the registry, we must introduce the necessary namespaces:

using Microsoft.Win32;

There are many registry-related classes in this namespace, which is enough for us to use ~ ~

2. Namespace provides a class: RegistryKey with which we can navigate to the first branch of the registry:

ClassesRoot, CurrentUser, Users, LocalMachine, CurrentConfig

Such as:

RegistryKey key = Registry.LocalMachine;

3. In the process of operation, sub-branches are involved, so we should use\\ to go deep, and a single\ will report errors!
4. Finally, call Close () of the RegistryKey object to close the registry modification ~ ~ ~
5. The following examples are all under the LocalMachine branch, please note.

1. Creation, opening, and deletion of C # registry keys

1. Create

Creating registry keys mainly uses CreateSubKey () method of RegistryKey. Such as:


RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.CreateSubKey("software\\test");
// In HKEY_LOCAL_MACHINE\SOFTWARE Create a new one named test The registry key of the. If it already exists, it will not affect! 

Step 2 Open

The OpenSubKey () method of RegistryKey is mainly used to open the registry key. Such as:

Note that if the registry key does not exist, this call to this method throws an exception


RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("software\\test",true);
// Note that this method can be followed by 1 Parameters of Boolean type, true Indicates that it can be written to. 

3. Delete

Deleting registry keys mainly uses DeleteSubKey () method of RegistryKey. Such as:


RegistryKey key = Registry.LocalMachine;
key.DeleteSubKey("software\\test",true); // This method has no return value, so it can be called directly 
key.Close();

Note that if the registry key does not exist, this call to this method throws an exception

2. Create (set value, modify), read and delete key values

1. Create (set values, modify)

The SetValue () method of RegistryKey is mainly used to create and modify key values


RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("software\\test",true); // The item must already exist 
software.SetValue("test", " Script House ");
// In HKEY_LOCAL_MACHINE\SOFTWARE\test Create under 1 The name is " test ", which is the key value of" Script Home ". If the key value already exists, the original key value will be modified and replaced, and if it does not exist, the key value will be created. 
//  Note: SetValue() And the first 3 Parameters, mainly used to set the type of key value, such as string, 2 Binary system, Dword Wait ~~ The default is a string. Such as: 
// software.SetValue("test", "0", RegistryValueKind.DWord); //2 Binary information 
Key.Close();

2. Read


string info = "";
RegistryKey Key;
Key = Registry.LocalMachine;
myreg = Key.OpenSubKey("software\\test");
// myreg = Key.OpenSubKey("software\\test",true);
info = myreg.GetValue("test").ToString();
myreg.Close();

info result: This site

3: Delete


RegistryKey delKey = Registry.LocalMachine.OpenSubKey("Software\\test", true);
delKey.DeleteValue("test");
delKey.Close();

Careful readers may notice that the OpenSubKey () method parameters in the second example are different from those in other examples.

If you want to modify the key value, including creating, setting and deleting the key value, you should add a Boolean parameter after the method and set it to true, which means that it can be written and changed; If you just read the key value can not add, at this time can write off, you can no longer write in the value (of course, you can add true)!

Some readers mentioned the problem of reading and writing default key values, mainly in setting, and setting the key name blank in the reading method is the operation of default key values.

Such as:

software.SetValue("", " Script House "); //  In HKEY_LOCAL_MACHINE\SOFTWARE\test Change the default key value to Script Home. Read similar! 

In addition, the default key value can not be deleted, so do not use DeleteValue () method to delete, will throw an exception!

3. Determine if a registry key exists


private bool IsRegeditItemExist() 
{ 
  string [] subkeyNames; 
  RegistryKey hkml = Registry.LocalMachine; 
  RegistryKey software = hkml.OpenSubKey("SOFTWARE"); 
  //RegistryKey software = hkml.OpenSubKey("SOFTWARE", true); 
  subkeyNames = software.GetSubKeyNames(); 
  // Gets the sequence of the names of all subitems under this item and passes it to the predetermined array  
  foreach (string keyName in subkeyNames)  
  // Traverse the entire array  
  { 
    if (keyName == "test") 
    // Determine the name of the subitem  
    {  
      hkml.Close(); 
      return true ; 
    } 
  } 
  hkml.Close(); 
  return false;  
}

4. Judge whether the key value exists or not


private bool IsRegeditKeyExit()
{
 string[] subkeyNames;
 RegistryKey hkml = Registry.LocalMachine;
 RegistryKey software = hkml.OpenSubKey("SOFTWARE\\test");
 //RegistryKey software = hkml.OpenSubKey("SOFTWARE\\test", true);
 subkeyNames = software.GetValueNames();
 // Gets the sequence of the names of all the key values under the item and passes it to the predetermined array 
 foreach (string keyName in subkeyNames)
 {
  if (keyName == "test") // Determine the name of the key value 
  {
    hkml.Close();
    return true;
  }
 }
 hkml.Close();
 return false;
}

Added: The x32 software operates the registry under the x64 system and will automatically turn to Wow6432Node. In order to control the non-turn, use the following code:


/// <summary>
///  Get the handle of the root node, and the constant is fixed 
/// </summary>
/// <param name="hive"></param>
/// <returns></returns>
public static IntPtr GetHiveHandle(RegistryHive hive)
{
  IntPtr preexistingHandle = IntPtr.Zero;
  IntPtr HKEY_CLASSES_ROOT = new IntPtr(-2147483648);
  IntPtr HKEY_CURRENT_USER = new IntPtr(-2147483647);
  IntPtr HKEY_LOCAL_MACHINE = new IntPtr(-2147483646);
  IntPtr HKEY_USERS = new IntPtr(-2147483645);
  IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(-2147483644);
  IntPtr HKEY_CURRENT_CONFIG = new IntPtr(-2147483643);
  IntPtr HKEY_DYN_DATA = new IntPtr(-2147483642);
  switch (hive)
  {
    case RegistryHive.ClassesRoot: preexistingHandle = HKEY_CLASSES_ROOT; break;
    case RegistryHive.CurrentUser: preexistingHandle = HKEY_CURRENT_USER; break;
    case RegistryHive.LocalMachine: preexistingHandle = HKEY_LOCAL_MACHINE; break;
    case RegistryHive.Users: preexistingHandle = HKEY_USERS; break;
    case RegistryHive.PerformanceData: preexistingHandle = HKEY_PERFORMANCE_DATA; break;
    case RegistryHive.CurrentConfig: preexistingHandle = HKEY_CURRENT_CONFIG; break;
    case RegistryHive.DynData: preexistingHandle = HKEY_DYN_DATA; break;
  }
  return preexistingHandle;
}

Use:


/// <summary>
///  Operation registry 
/// </summary>
/// <param name="hive"> The name of the root level </param>
/// <param name="path"> Does not include the name of the root level </param>
/// <param name="parameters"> Items / (Value / Value type)   Parameter </param>
/// <param name="view"> Registry view </param>
[RegistryPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
public static void OperateReg(RegistryHive hive, string path, Dictionary<string, string[]> parameters, RegistryView view)
{
  SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true);
  RegistryKey r = RegistryKey.FromHandle(handle, view).CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree);
//1 The general situation is to use the following code: 
//RegistryKey rk = Registry.LocalMachine.CreateSubKey(path);
  if (parameters == null && parameters.Count <= 0)
    return;
  List<string> keys = parameters.Keys.ToList();
  for (int i = 0; i < parameters.Count; i++)
  {  //string to RegistryValueKind
    RegistryValueKind rv = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), parameters[keys[i]][1].ToString(), true);
    r.SetValue(keys[i], parameters[keys[i]][0], rv);
  }
}

Examples:


RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("software\\test",true);
// Note that this method can be followed by 1 Parameters of Boolean type, true Indicates that it can be written to. 

0

Just after testing, I don't need GetHiveHandl () (I don't know what I need);

The 12 lines of code in the OperateReg () method are changed to


RegistryKey r = RegistryKey.OpenBaseKey(hive, view).CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree);

I hope this article is helpful to everyone's C # programming.


Related articles: