我想打開一個符號鏈接的注冊表項。
根據微軟的說法,我需要用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)
我能想到的唯一方法是使用 p\invoke 但也許我錯過了它,并且 C# 類中有一個選項。
uj5u.com熱心網友回復:
您無法使用正常RegistryKey功能執行此操作。簽入源代碼后,似乎該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. 不要忘記using在回傳的地方加上一個RegistryKey:
using (var key = Registry.CurrentUser.OpenSubKeySymLink(@"SOFTWARE\Microsoft\myKey", RegistryRights.ReadKey))
{
// do stuff with key
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411752.html
標籤:
