你不能用正常的方式做到这一点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
}