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

net,invoke · 浏览次数 : 0

小编点评

**注册表key失败。 Failed to create registry key.\n** **参数:** * **root**:要删除的注册表根的路径。 * **subKey**:要删除的注册表键的路径。 **异常类型:** * **Exception**:如果注册表操作失败,抛出该异常。 **方法:** * **DeleteKey()**:根据给定的根路径和键路径删除注册表键。 * **SetValue()**:根据给定的根路径、键路径和值名设置注册表值。 * **GetValue()**:根据给定的根路径、键路径和值名获取注册表值。 * **DeleteValue()**:根据给定的根路径、键路径和值名删除注册表值。

正文

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

当前注册表主目录:

引用包 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);
    }

 

 

 

与.NET使用P/Invoke来实现注册表的增、删、改、查功能相似的内容:

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

注册表可以用来进行存储一些程序的信息,例如用户的权限、或者某些值等,可以根据个人需要进行存储和删减。 当前注册表主目录: 引用包 Wesky.Net.OpenTools 1.0.5或者以上版本 操作演示: 创建注册表项 设置注册表值 读取注册表值 删除注册表值 删除注册表项 操作演示代码 IRegi

.NET使用CsvHelper快速读取和写入CSV文件

前言 在日常开发中使用CSV文件进行数据导入和导出、数据交换是非常常见的需求,今天我们来讲讲在.NET中如何使用CsvHelper这个开源库快速实现CSV文件读取和写入。 CsvHelper类库介绍 CsvHelper是一个.NET开源、快速、灵活、高度可配置、易于使用的用于读取和写入CSV文件的类

.NET使用原生方法实现文件压缩和解压

前言 在.NET中实现文件或文件目录压缩和解压可以通过多种方式来完成,包括使用原生方法(System.IO.Compression命名空间中的类)和第三方库(如:SharpZipLib、SharpCompress、K4os.Compression.LZ4等)。本文我们主要讲的是如何使用.NET原生方

.NET 使用 OpenTelemetry metrics 监控应用程序指标

上一次我们讲了 OpenTelemetry Logs 与 OpenTelemetry Traces。今天继续来说说 OpenTelemetry Metrics。 随着现代应用程序的复杂性不断增加,对于性能监控和故障排除的需求也日益迫切。在 .NET 生态系统中,OpenTelemetry Metri

在 .NET 7上使用 WASM 和 WASI

WebAssembly(WASM)和WebAssembly System Interface(WASI)为开发人员开辟了新的世界。.NET 开发人员在 Blazor WebAssembly 发布时熟悉了 WASM。Blazor WebAssembly 在浏览器中基于 WebAssembly 的 .N

.net使用nacos配置,手把手教你分布式配置中心

.net使用nacos配置,手把手教你分布式配置中心 Nacos是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。 这么优秀的分布式服务管理平台,怎么能不接入呢? nacos的安装和使用这里就不细说了,可以参考网上教程和官方文档。https://nacos.io/zh-cn/docs

C#/.NET这些实用的技巧和知识点你都知道吗?

前言 今天大姚给大家分享一些C#/.NET中的实用的技巧和知识点,它们可以帮助我们提升代码质量和编程效率,希望可以帮助到有需要的同学。 .NET使用CsvHelper快速读取和写入CSV文件 本文主要讲解.NET中如何使用CsvHelper这个开源库快速实现CSV文件读取和写入。 https://m

【译】使用 .NET Aspire 和 Visual Studio 开发云原生应用

我们很高兴地宣布 .NET Aspire 发布,它扩展了 Visual Studio 在云原生应用程序开发方面的能力。.NET Aspire 提供了一个框架和工具,以一种独特的方式,使分布式 .NET 应用程序更容易构建、部署和管理。这种集成旨在使云原生应用程序的开发更加简单和高效。

Python使用.NET开发的类库来提高你的程序执行效率

Python由于本身的特性原因,执行程序期间可能效率并不是很理想。在某些需要自己提高一些代码的执行效率的时候,可以考虑使用C#、C++、Rust等语言开发的库来提高python本身的执行效率。接下来,我演示一种使用.NET平台开发的类库,来演示一下Python访问.NET类库的操作实现。类库演示包括

.NET 中使用 OpenTelemetry Traces 追踪应用程序

上一次我们讲了 OpenTelemetry Logs。今天继续来说说 OpenTelemetry Traces。 在今天的微服务和云原生环境中,理解和监控系统的行为变得越来越重要。在当下我们实现一个功能可能需要调用了 N 个方法,涉及到 N 个服务。方法之间的调用如蜘蛛网一样。分布式追踪这个时候就至