如何在C#注冊表類中使用REG_OPTION_OPEN_LINK [英] 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!
查看全文