如何在C#注册表类中使用REG_OPTION_OPEN_LINK
- 作者: 快乐的小2鸟
- 来源: 51数据库
- 2022-10-19
问题描述
我要打开一个符号链接的注册表项。
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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0
