.NET使用advapi32.dll的API实现注册表的增、删、改、查功能

注册表可以用来进行存储一些程序的信息,例如用户的权限、或者某些值等,可以根据个人需要进行存储和删减。

当前注册表主目录:

引用包 Wesky.Net.OpenTools 1.0.5或者以上版本

 操作演示:

创建注册表项

设置注册表值

读取注册表值

删除注册表值

删除注册表项

操作演示代码

复制代码
IRegistryManager registryManager = new RegistryManager();

// 创建注册表项
// registryManager.CreateKey(RegistryRoot.CurrentUser, @"Wesky\MyApp");

// 设置注册表值
// registryManager.SetValue(RegistryRoot.CurrentUser, @"Wesky\MyApp", "MyValue", "Hello, Registry!");

// 读取注册表值
// var value = registryManager.GetValue(RegistryRoot.CurrentUser, @"Wesky\MyApp", "MyValue");
// Console.WriteLine($"读取到的注册表值:{value}");

// 删除注册表值
// registryManager.DeleteValue(RegistryRoot.CurrentUser, @"Wesky\MyApp", "MyValue");

// 删除注册表项
registryManager.DeleteKey(RegistryRoot.CurrentUser, @"Wesky\MyApp");
Console.WriteLine("Over");
Console.ReadKey();
复制代码

 

 

核心包内源码:

复制代码
 [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    private static extern int RegCreateKeyEx(
        IntPtr hKey,
        string lpSubKey,
        int Reserved,
        string lpClass,
        int dwOptions,
        int samDesired,
        IntPtr lpSecurityAttributes,
        out IntPtr phkResult,
        out int lpdwDisposition);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    private static extern int RegOpenKeyEx(
        IntPtr hKey,
        string lpSubKey,
        int ulOptions,
        int samDesired,
        out IntPtr phkResult);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    private static extern int RegCloseKey(IntPtr hKey);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    private static extern int RegSetValueEx(
        IntPtr hKey,
        string lpValueName,
        int Reserved,
        int dwType,
        byte[] lpData,
        int cbData);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    private static extern int RegGetValue(
        IntPtr hKey,
        string lpSubKey,
        string lpValue,
        int dwFlags,
        out int pdwType,
        StringBuilder pvData,
        ref int pcbData);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    private static extern int RegDeleteKey(IntPtr hKey, string lpSubKey);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    private static extern int RegDeleteValue(IntPtr hKey, string lpValueName);

    /// <summary>
    /// 获取注册表根键
    /// Get registry root key
    /// </summary>
    /// <param name="root"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentOutOfRangeException"></exception>
    private IntPtr GetRegistryRootKey(RegistryRoot root)
    {
        switch (root)
        {
            case RegistryRoot.ClassesRoot:
                return HKEY_CLASSES_ROOT;
            case RegistryRoot.CurrentUser:
                return HKEY_CURRENT_USER;
            case RegistryRoot.LocalMachine:
                return HKEY_LOCAL_MACHINE;
            case RegistryRoot.Users:
                return HKEY_USERS;
            case RegistryRoot.CurrentConfig:
                return HKEY_CURRENT_CONFIG;
            default:
                throw new ArgumentOutOfRangeException(nameof(root), root, null);
        }
    }

    /// <summary>
    /// 创建注册表键
    /// Create registry key
    /// </summary>
    /// <param name="root"></param>
    /// <param name="subKey"></param>
    /// <exception cref="Exception"></exception>
    public void CreateKey(RegistryRoot root, string subKey)
    {
        IntPtr hKey = GetRegistryRootKey(root);
        int result = RegCreateKeyEx(hKey, subKey, 0, null, REG_OPTION_NON_VOLATILE, KEY_WRITE, IntPtr.Zero, out IntPtr phkResult, out _);

        if (result != ERROR_SUCCESS)
        {
            throw new Exception("创建注册表key失败。 Failed to create registry key.");
        }

        RegCloseKey(phkResult);
    }

    /// <summary>
    /// 删除注册表键
    /// Delete registry key
    /// </summary>
    /// <param name="root"></param>
    /// <param name="subKey"></param>
    /// <exception cref="Exception"></exception>
    public void DeleteKey(RegistryRoot root, string subKey)
    {
        IntPtr hKey = GetRegistryRootKey(root);
        int result = RegDeleteKey(hKey, subKey);

        if (result != ERROR_SUCCESS)
        {
            throw new Exception("删除注册表key失败。Failed to delete registry key.");
        }
    }

    /// <summary>
    /// 设置注册表值
    /// Set registry value
    /// </summary>
    /// <param name="root"></param>
    /// <param name="subKey"></param>
    /// <param name="valueName"></param>
    /// <param name="value"></param>
    /// <exception cref="Exception"></exception>
    public void SetValue(RegistryRoot root, string subKey, string valueName, string value)
    {
        IntPtr hKey = GetRegistryRootKey(root);

        int result = RegOpenKeyEx(hKey, subKey, 0, KEY_WRITE, out IntPtr phkResult);
        if (result != ERROR_SUCCESS)
        {
            throw new Exception("打开注册表key失败。Failed to open registry key.");
        }

        byte[] data = Encoding.Unicode.GetBytes(value);
        result = RegSetValueEx(phkResult, valueName, 0, REG_SZ, data, data.Length);

        if (result != ERROR_SUCCESS)
        {
            throw new Exception("设置注册表值失败。Failed to set registry value.");
        }

        RegCloseKey(phkResult);
    }

    /// <summary>
    /// 获取注册表值
    /// Get registry value
    /// </summary>
    /// <param name="root"></param>
    /// <param name="subKey"></param>
    /// <param name="valueName"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public string GetValue(RegistryRoot root, string subKey, string valueName)
    {
        IntPtr hKey = GetRegistryRootKey(root);

        int result = RegOpenKeyEx(hKey, subKey, 0, KEY_READ, out IntPtr phkResult);
        if (result != ERROR_SUCCESS)
        {
            throw new Exception("打开注册表key失败。Failed to open registry key.");
        }

        int type = 0;
        int size = 1024;
        StringBuilder data = new StringBuilder(size);

        result = RegGetValue(phkResult, null, valueName, RRF_RT_REG_SZ, out type, data, ref size);

        if (result != ERROR_SUCCESS)
        {
            throw new Exception("获取注册表的值失败。Failed to get registry value.");
        }

        RegCloseKey(phkResult);

        return data.ToString();
    }

    /// <summary>
    /// 删除注册表值
    /// Delete registry value
    /// </summary>
    /// <param name="root"></param>
    /// <param name="subKey"></param>
    /// <param name="valueName"></param>
    /// <exception cref="Exception"></exception>
    public void DeleteValue(RegistryRoot root, string subKey, string valueName)
    {
        IntPtr hKey = GetRegistryRootKey(root);

        int result = RegOpenKeyEx(hKey, subKey, 0, KEY_WRITE, out IntPtr phkResult);
        if (result != ERROR_SUCCESS)
        {
            throw new Exception("打开注册表key失败。Failed to open registry key.");
        }

        result = RegDeleteValue(phkResult, valueName);

        if (result != ERROR_SUCCESS)
        {
            throw new Exception("删除注册表的值失败。Failed to delete registry value.");
        }

        RegCloseKey(phkResult);
    }
复制代码

 

 

 

 

2024-05-15 13:56:10【出处】:https://www.cnblogs.com/weskynet/p/18191869

=======================================================================================

.NET使用P/Invoke来实现注册表的增、删、改、查功能

在.NET中,你可以使用P/Invoke来调用Windows API来实现对注册表的增、删、改、查操作。以下是一些基本的示例代码:

using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
 
class RegistryOperations
{
    // 注册表项基本路径
    private const string baseRegistryPath = @"Software\YourSoftware";
 
    // P/Invoke 调用 Windows API 来创建或打开注册表项
    [DllImport("advapi32.dll")]
    static extern int RegCreateKeyEx(
        uint hKey,
        string subKey,
        int reserved,
        string lpClass,
        int dwOptions,
        int samDesired,
        int lpSecurityAttributes,
        out int phkResult,
        out int lpdwDisposition
    );
 
    // P/Invoke 调用 Windows API 来关闭注册表项句柄
    [DllImport("advapi32.dll", SetLastError = true)]
    static extern int RegCloseKey(int hKey);
 
    // P/Invoke 调用 Windows API 来设置注册表项值
    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    static extern int RegSetValueEx(
        int hKey,
        string lpValueName,
        int Reserved,
        int dwType,
        string lpData,
        int cbData
    );
 
    // P/Invoke 调用 Windows API 来获取注册表项值
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int RegQueryValueEx(
        int hKey,
        string lpValueName,
        int lpReserved,
        out int lpType,
        System.Text.StringBuilder lpData,
        ref int lpcbData
    );
 
    // P/Invoke 调用 Windows API 来删除注册表项值
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int RegDeleteValue(int hKey, string lpValueName);
 
    // 创建或打开注册表项
    public static int CreateOrOpenRegistryKey(string subKey)
    {
        int hkey, disposition;
        string keyPath = baseRegistryPath + "\\" + subKey;
        int result = RegCreateKeyEx(0x80000001, keyPath, 0, null, 0, 0xF003F, 0, out hkey, out disposition);
        return hkey;
    }
 
    // 关闭注册表项句柄
    public static int CloseRegistryKey(int hKey)
    {
        return RegCloseKey(hKey);
    }
 
    // 设置注册表项值
    public static int SetRegistryValue(int hKey, string valueName, string value)
    {
        return RegSetValueEx(hKey, valueName, 0, 1, value, value.Length);
    }
 
    // 获取注册表项值
    public static string GetRegistryValue(int hKey, string valueName)
    {
        int type;
        int size = 1024;
        System.Text.StringBuilder data = new System.Text.StringBuilder(size);
        RegQueryValueEx(hKey, valueName, 0, out type, data, ref size);
        return data.ToString();
    }
 
    // 删除注册表项值
    public static int DeleteRegistryValue(int hKey, string valueName)
    {
        return RegDeleteValue(hKey, valueName);
    }
}

在使用这些方法时,你需要先打开注册表项的句柄,然后进行相应的操作,操作完成后不要忘记关闭句柄。

请注意,直接操作注册表可能会影响系统稳定性和安全性,应谨慎使用。此外,这些代码示

提示:AI自动生成,仅供参考
 
 
 

posted on 2024-05-15 13:59  jack_Meng  阅读(49)  评论(0编辑  收藏  举报

导航