eduics 2021-10-04 01:43 采纳率: 42.9%
浏览 40
已结题

C#语言如何实现利用windows自带的动态链接库实现对注册表的增删改查

C#语言如何实现利用windows自带的动态链接库实现对注册表的增删改查

  • 写回答

1条回答 默认 最新

  • 神仙别闹 2021-10-04 02:13
    关注

    定义注册表操作类RegUtil

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using Microsoft.Win32;
    
    namespace ToolUtils
    {
        public static class RegUtil
        {
            static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000));
            static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001));
            static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
            static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));
            static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004));
            static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005));
            static readonly IntPtr HKEY_DYN_DATA = new IntPtr(unchecked((int)0x80000006));
    
            // 获取操作Key值句柄 
            [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int RegOpenKeyEx(IntPtr hKey, string lpSubKey, uint ulOptions, int samDesired, out IntPtr phkResult);
    
            //创建或打开Key值
            [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int RegCreateKeyEx(IntPtr hKey, string lpSubKey, int reserved, string type, int dwOptions, int REGSAM, IntPtr lpSecurityAttributes, out IntPtr phkResult,
                                                     out int lpdwDisposition);
    
            //关闭注册表转向(禁用特定项的注册表反射)
            [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int RegDisableReflectionKey(IntPtr hKey);
    
            //使能注册表转向(开启特定项的注册表反射)
            [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int RegEnableReflectionKey(IntPtr hKey);
    
            //获取Key值(即:Key值句柄所标志的Key对象的值)
            [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int RegQueryValueEx(IntPtr hKey, string lpValueName, int lpReserved, out uint lpType, System.Text.StringBuilder lpData, ref uint lpcbData);
    
            //设置Key值
            [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int RegSetValueEx(IntPtr hKey, string lpValueName, uint unReserved, uint unType, byte[] lpData, uint dataCount);
    
            //关闭Key值
            [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int RegCloseKey(IntPtr hKey);
    
            public static IntPtr TransferKeyName(string keyName)
            {
                IntPtr ret = IntPtr.Zero;
                switch (keyName)
                {
                    case "HKEY_CLASSES_ROOT":
                        ret = HKEY_CLASSES_ROOT;
                        break;
                    case "HKEY_CURRENT_USER":
                        ret = HKEY_CURRENT_USER;
                        break;
                    case "HKEY_LOCAL_MACHINE":
                        ret = HKEY_LOCAL_MACHINE;
                        break;
                    case "HKEY_USERS":
                        ret = HKEY_USERS;
                        break;
                    case "HKEY_PERFORMANCE_DATA":
                        ret = HKEY_PERFORMANCE_DATA;
                        break;
                    case "HKEY_CURRENT_CONFIG":
                        ret = HKEY_CURRENT_CONFIG;
                        break;
                    case "HKEY_DYN_DATA":
                        ret = HKEY_DYN_DATA;
                        break;
                    default:
                        ret = HKEY_LOCAL_MACHINE;
                        break;
                }
                return ret;
            }
    
            /// <summary>
            /// 设置64位注册表
            /// </summary>
            /// <param name="key"></param>
            /// <param name="subKey"></param>
            /// <param name="name"></param>
            /// <param name="value"></param>
            /// <returns></returns>
            public static int Set64BitRegistryKey(string key, string subKey, string name, string value)
            {
                int STANDARD_RIGHTS_ALL = (0x001F0000);
                int KEY_QUERY_VALUE = (0x0001);
                int KEY_SET_VALUE = (0x0002);
                int KEY_CREATE_SUB_KEY = (0x0004);
                int KEY_ENUMERATE_SUB_KEYS = (0x0008);
                int KEY_NOTIFY = (0x0010);
                int KEY_CREATE_LINK = (0x0020);
                int SYNCHRONIZE = (0x00100000);
                int KEY_WOW64_64KEY = (0x0100);
                int REG_OPTION_NON_VOLATILE = (0x00000000);
                int KEY_ALL_ACCESS = (STANDARD_RIGHTS_ALL | KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY | KEY_ENUMERATE_SUB_KEYS
                                     | KEY_NOTIFY | KEY_CREATE_LINK) & (~SYNCHRONIZE);
    
                int ret = 0;
                try
                {
                    //将Windows注册表主键名转化成为不带正负号的整形句柄(与平台是32或者64位有关)
                    IntPtr hKey = TransferKeyName(key);
    
                    //声明将要获取Key值的句柄 
                    IntPtr pHKey = IntPtr.Zero;
    
                    //获得操作Key值的句柄
                    int lpdwDisposition = 0;
                    ret = RegCreateKeyEx(hKey, subKey, 0, "", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS | KEY_WOW64_64KEY, IntPtr.Zero, out pHKey, out lpdwDisposition);
                    if (ret != 0)
                    {
                        Log2.Log(string.Format("Unable to create key {0} - {1}: {2}!", key, subKey, ret));
                        return ret;
                    }
    
                    //关闭注册表转向(禁止特定项的注册表反射)
                    RegDisableReflectionKey(pHKey);
    
                    //设置访问的Key值
                    uint REG_SZ = 1;
                    byte[] data = Encoding.Unicode.GetBytes(value);
    
                    RegSetValueEx(pHKey, name, 0, REG_SZ, data, (uint)data.Length);
    
                    //打开注册表转向(开启特定项的注册表反射)
                    RegEnableReflectionKey(pHKey);
    
                    RegCloseKey(pHKey);
                }
                catch (Exception ex)
                {
                    Log2.Log(ex.ToString());
                    return -1;
                }
    
                return ret;
            }
    
            public static void SetRegistryKey(string key, string subKey, string name, string value)
            {
                Log2.Log("SetRegistryKey start.");
                if (System.IntPtr.Size == 8)
                {
                    // 写SOFTWARE\Huawei\VirtualDesktopAgent,需要关闭注册表重定向,再写64位路径的注册表
                    int ret = RegUtil.Set64BitRegistryKey(key, subKey, name, value);
                    if (ret != 0)
                    {
                        Log2.Log(string.Format("Failed to write Reg {0}\\{1}\\{2},return {3}", key, subKey, name, ret));
                    }
                }
    
                try
                {
                    Microsoft.Win32.Registry.SetValue(key + "\\" + subKey, name, value);
                }
                catch (Exception ex)
                {
                    Log2.Log(ex.ToString());
                }
    
                Log2.Log("SetRegistryKey exit.");
            }
    
            public static string GetRegistryValue(string path, string key)
            {
                RegistryKey regkey = null;
                try
                {
                    regkey = Registry.LocalMachine.OpenSubKey(path);
                    if (regkey == null)
                    {
                        Log2.Log("Cannot find Registry path:" + path);
                        return null;
                    }
    
                    object val = regkey.GetValue(key);
                    if (val == null)
                    {
                        Log2.Log("Cannot find Registry key:" + key);
                        return null;
                    }
    
                    return val.ToString();
                }
                catch (Exception ex)
                {
                    Log2.Log(ex.ToString());
                    return null;
                }
                finally
                {
                    if (regkey != null)
                    {
                        regkey.Close();
                    }
                }
            }
        }
    }
    
    

    使用

    //定义
    string Winrarpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\WinRAR archiver";
    string key = "DisplayVersion";
    
    //获取注册表值(32位和64位都可以)
    string value = Common.GetRegistryValue(Winrarpath,key);
    
    //修改注册表
     string value = "修改内容";
    Common.SetRegistryKey("HKEY_LOCAL_MACHINE", Winrarpath, "DisPlayVersion", value);
    string newValue = Common.GetRegistryValue(Winrarpath, "DisPlayVersion");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月3日
  • 已采纳回答 10月26日
  • 创建了问题 10月4日

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效