C#操作注册表简单教程(附带操作某数据库客户端注册表以实现重置试用期的效果)
前言:
使用Windows系统,经常会遇到需要做注册表的操作。例如,一些软件需要修改注册表、自己编写的软件需要新建注册表进行写入注册信息等等。以下内容以某常见的数据库操作客户端为例,做一个注册表操作的学习。
1、例如,找一个已经注册表过期的软件,记录一下时间和当前过期的效果。
2、参考C#操作注册表官方文档:
3、官方示例代码:
using System;
using System.Security.Permissions;
using Microsoft.Win32;
class RegKey
{
static void Main()
{
// Create a subkey named Test9999 under HKEY_CURRENT_USER.
RegistryKey test9999 =
Registry.CurrentUser.CreateSubKey("Test9999");
// Create two subkeys under HKEY_CURRENT_USER\Test9999. The
// keys are disposed when execution exits the using statement.
using(RegistryKey
testName = test9999.CreateSubKey("TestName"),
testSettings = test9999.CreateSubKey("TestSettings"))
{
// Create data for the TestSettings subkey.
testSettings.SetValue("Language", "French");
testSettings.SetValue("Level", "Intermediate");
testSettings.SetValue("ID", 123);
}
// Print the information from the Test9999 subkey.
Console.WriteLine("There are {0} subkeys under {1}.",
test9999.SubKeyCount.ToString(), test9999.Name);
foreach(string subKeyName in test9999.GetSubKeyNames())
{
using(RegistryKey
tempKey = test9999.OpenSubKey(subKeyName))
{
Console.WriteLine("\nThere are {0} values for {1}.",
tempKey.ValueCount.ToString(), tempKey.Name);
foreach(string valueName in tempKey.GetValueNames())
{
Console.WriteLine("{0,-8}: {1}", valueName,
tempKey.GetValue(valueName).ToString());
}
}
}
using(RegistryKey
testSettings = test9999.OpenSubKey("TestSettings", true))
{
// Delete the ID value.
testSettings.DeleteValue("id");
// Verify the deletion.
Console.WriteLine((string)testSettings.GetValue(
"id", "ID not found."));
}
// Delete or close the new subkey.
Console.Write("\nDelete newly created registry key? (Y/N) ");
if(Char.ToUpper(Convert.ToChar(Console.Read())) == 'Y')
{
Registry.CurrentUser.DeleteSubKeyTree("Test9999");
Console.WriteLine("\nRegistry key {0} deleted.",
test9999.Name);
}
else
{
Console.WriteLine("\nRegistry key {0} closed.",
test9999.ToString());
test9999.Close();
}
}
}
4、做一个测试清理Navicat注册表的demo,当作学习使用。
核心代码:
RegistryKey regKey = Registry.CurrentUser;
RegistryKey regKey2 = regKey.OpenSubKey(@"Software\Classes\CLSID",true);
string[] keyNameColl;
keyNameColl = regKey2.GetSubKeyNames();
List<string> keyNames = new List<string>();
foreach (string key in keyNameColl) {
var subKeys = regKey2.OpenSubKey(key,true);
var subKeyNames = subKeys.GetSubKeyNames();
if(subKeyNames!=null && subKeyNames.Length==1 && subKeyNames[0] == "Info")
{
keyNames.Add(key);
}
subKeys?.Close();
}
foreach (var key in keyNames) {
regKey2.DeleteSubKeyTree(key,false);
Console.WriteLine($"[HKEY_CURRENT_USER\\Software\\Classes\\CLSID\\{key}]");
}
regKey2.Close();
regKey.Close();
5、写好代码以后,编译成功即可使用。
6、执行完毕以后,进行重写打开Navicat15验证下,发现试用期被重置了,说明注册表操作是成功的。
【警告】该操作仅用于学习用途,旨在帮助大家熟悉使用C#进行注册表的操作,严禁用于其他非法用途。
本文作者:Wesky
微信号:WeskyNet001
公众号:Dotnet Dancer
文章链接:https://www.cnblogs.com/weskynet/p/17137077.html
欢迎扫一扫关注公众号,发现更多其他技术分享