问题描述
我要打开一个符号链接的注册表项。
According to Microsoft我需要使用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)
我能想到的唯一方法是使用pInvoke,但可能我错过了它,C#类中有一个选项。
推荐答案
您无法使用正常的RegistryKey函数执行此操作。签入the source code后,ulOptions参数似乎始终作为0传递。
唯一的方法是自己调用RegOpenKeyEx,并将结果SafeRegistryHandle传递给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。别忘了在返回的RegistryKey上加一个using:
using (var key = Registry.CurrentUser.OpenSubKeySymLink(@"SOFTWAREMicrosoftmyKey", RegistryRights.ReadKey))
{
// do stuff with key
}
;
快乐的小2鸟