如何在 C# 注册表类中使用 REG_OPTION_OPEN_LINK

2024-04-01

我想打开一个符号链接的注册表项。
据微软称 https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexw#parameters我需要使用REG_OPTION_OPEN_LINK打开它。
我搜索了一个选项将其添加到OpenSubKey功能,但我没有找到选项。只有五个重载函数,但它们都不允许添加可选参数:

Microsoft.Win32.Registry.CurrentUser.OpenSubKey(string name)
Microsoft.Win32.Registry.CurrentUser.OpenSubKey(string name, bool writable)
Microsoft.Win32.Registry.CurrentUser.OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck)
Microsoft.Win32.Registry.CurrentUser.OpenSubKey(string name, RegistryRights rights)
Microsoft.Win32.Registry.CurrentUser.OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)

我能想到的唯一方法是使用 p\invoke 但也许我错过了它,并且 C# 类中有一个选项。


你不能用正常的方式做到这一点RegistryKey功能。已办理登机手续源代码 https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs,似乎ulOptions参数始终传递为0.

唯一的办法就是打电话RegOpenKeyEx自己,并通过结果SafeRegistryHandle to RegistryKey.FromHandle

using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.ComponentModel;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)]
static extern int RegOpenKeyExW(SafeRegistryHandle hKey, String lpSubKey,
    int ulOptions, int samDesired, out SafeRegistryHandle hkResult);

public static RegistryKey OpenSubKeySymLink(this RegistryKey key, string name, RegistryRights rights = RegistryRights.ReadKey, RegistryView view = 0)
{
    const int REG_OPTION_OPEN_LINK = 0x0008;
    var error = RegOpenKeyExW(key.Handle, name, REG_OPTION_OPEN_LINK, ((int)rights) | ((int)view), out var subKey);
    if (error != 0)
    {
        subKey.Dispose();
        throw new Win32Exception(error);
    }
    return RegistryKey.FromHandle(subKey);  // RegistryKey will dispose subKey
}

它是一个扩展函数,因此您可以在现有的子键或主键之一上调用它,例如Registry.CurrentUser https://learn.microsoft.com/en-us/dotnet/api/microsoft.win32.registry.currentuser?view=net-6.0。别忘了放一个using在返回的RegistryKey:

using (var key = Registry.CurrentUser.OpenSubKeySymLink(@"SOFTWARE\Microsoft\myKey", RegistryRights.ReadKey))
{
    // do stuff with key
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 C# 注册表类中使用 REG_OPTION_OPEN_LINK 的相关文章

随机推荐