Home>

Let's use it below.C#registry operation under managed language,The main contents include:the creation of registry keys,Open and delete, create key values ​​(set values, modify), read and delete, determine whether a registry key exists, and determine whether a key value exists.

Ready to work:

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

using microsoft.win32;

There are many registry-related classes in this namespace.Enough for us to use ~~

2. A class is provided in the namespace:registrykey Using it we can locate the very first branch of the registry:

classesroot, currentuser, users, localmachine, currentconfig

Such as:

registrykey key=registry.localmachine;

3. Sub-branch is involved in the operation,To go deeper with \\,Single \ will report an error!

4. Finally, close () of the registry key object is called to close the modification of the registry ~~~

5. The following examples are all under the localmachine branch, please note.

First, the creation of c#registry keys,Open and delete

Create

The registry key is created using the registry key's createsubkey () method. Such as:

registrykey key=registry.localmachine;
registrykey software=key.createsubkey ("software \\ test");
//Create a new registry key named test under hkey_local_machine \ software.
No impact if it already exists!

Open

The registry key is used to open the registrykey's opensubkey () method. Such as:

Note that if the key does not exist,This call to this method will throw an exception

registrykey key=registry.localmachine;
registrykey software=key.opensubkey ("software \\ test", true);
//Note that this method can also have a boolean parameter,true means it can be written.

3. Delete

Deleting a registry key mainly uses the deletekey () method of registrykey. Such as:

registrykey key=registry.localmachine;
key.deletesubkey ("software \\ test", true);//This method has no return value,Just call it directly
key.close ();

Note that if the key does not exist,This call to this method will throw an exception

Second, the creation of key values ​​(set values, modify), read and delete

1. Create (set value, modify)

The key value creation and modification operations mainly use the setkey () method of registrykey

registrykey key=registry.localmachine;
registrykey software=key.opensubkey ("software \\ test", true);//The item must already exist
//Note:setvalue () has a third parameter,Mainly used to set the type of key value,Such as:string, binary, dword, etc. ~~ The default is a string.
Such as:
//software.setvalue ("test", "0", registryvaluekind.dword);//binary information
key.close ();

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 ();

3:delete

registrykey delkey ​​= registry.localmachine.opensubkey ("software \\ test", true);
delkey.deletevalue ("test");
delkey.close ();

Attentive readers may find that the parameters of the opensubkey () method in the second example are different from other examples.

If i want to modify the key value,Including creating, setting, deleting key values, etc., you must add a Boolean parameter after the method.Set to true, which means it can be written and changed;If you just read the key value, you don't need to add it.Write can be closed at this time,You can't write any more values ​​(of course, you can also add true)!

Also readers mentioned the problem of reading and writing default key values,Setting the key name to blank in the setting and reading methods is the operation of the default key value.

Such as:

In addition, the default key value cannot be deleted.So don't use deletevalue () method to delete,Will throw an exception!

Third, determine whether the 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 ();
  //Get the sequence of names of all children under the item,And passed to the predetermined array
  foreach (string keyname in subkeynames)
  //traverse the entire array
  {
    if (keyname == "test")
    //Judge the name of the child
    {
      hkml.close ();
      return true;
    }
  }
  hkml.close ();
  return false;
}

Fourth, determine whether the key value exists

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 ();
 //Get the sequence of names of all key values ​​under the item,And passed to the predetermined array
 foreach (string keyname in subkeynames)
 {
  if (keyname == "test") //Judge the name of the key
  {
    hkml.close ();
    return true;
  }
 }
 hkml.close ();
 return false;
}

supplement:The x32 software operates the registry under the x64 system,Will automatically turn to wow6432node, in order to control not turn,Use the following code:

///<summary>
///get the handle of the root node,Constants are 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>
///operate the registry
///</summary>
///<param name="hive">name of root level</param>
///<param name="path">does not include the name of the root level</param>
///<param name="parameters">item/(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);
//General situation is to use the following code:
//registrykey rk=registry.localmachine.createsubkey (path);
  if (parameters == null&¶meters.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);
  }
}

example:

public static void registerscreencapture (string targetdir, string guid, bool is64bitlync)
{
  if (string.isnullorempty (guid))
    guid="{541a4dc3-50dc-4b4f-a38d-0ed1d360ca6b}";
  dictionary<string, string []>paracapture=new dictionary<string, string []>();
  paracapture ["name"]=new string [] {"screencapture", registryvaluekind.string.tostring ()};
  paracapture ["path"]=new string [] {string.format ("{0} icolync.screencapture.exe", targetdir), registryvaluekind.string.tostring ()};
  paracapture ["extensiblemenu"]=new string [] {"conversationwindowactions", registryvaluekind.string.tostring ()};
  paracapture ["sessiontype"]=new string [] {"0", registryvaluekind.dword.tostring ()};
  registryview rv;
  if (is64bitlync)
    rv=registryview.registry64;
  else
    rv=registryview.default;
  operatereg (registryhive.localmachine, string.format (@ "software \ microsoft \ office \ 15.0 \ lync \ sessionmanager \ apps \ {0}", guid), paracapture, rv);
}

Just tested,You don't need gethivehandl () (I don't know what it takes);

The one or two lines of code in the operatereg () method are changed to

registrykey r=registrykey.openbasekey (hive, view) .createsubkey (path, registrykeypermissioncheck.readwritesubtree);
c
  • Previous Detailed Java operation Properties configuration file
  • Next Summary of js operation array function examples