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
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
