How to use REG_OPTION_OPEN_LINK in C# Registry class(如何在C#注册表类中使用REG_OPTION_OPEN_LINK)
问题描述
我要打开一个符号链接的注册表项。
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
}
这篇关于如何在C#注册表类中使用REG_OPTION_OPEN_LINK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在C#注册表类中使用REG_OPTION_OPEN_LINK
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
