将注册表写入hkey_current_user而不是hkey_users

时间:2016-09-01 01:43:11

标签: c# registry

我尝试将注册表子项及其对应的值写入注册表,如下所示:

Microsoft.Win32.RegistryKey mykey;
mykey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\Muhil Software");
mykey.SetValue("Muhil", "TEST");
mykey.close();

如您所见,我使用CurrentUser将值写入HKEY_CURRENT_USERHKEY_CURRENT_USER中没有任何内容。然后我检查了HKEY_USERS中的子项,发现密钥是在那里写的。

1 个答案:

答案 0 :(得分:2)

您的安装程序不会在登录的用户会话下运行,而是在本地系统会话下运行。这就解释了为什么HKCU指向其他注册表配置单元。

要打开已登录用户的注册表项,您需要打开此注册表项HKU/<LOGGED_ON_USER_SID>。借助Windows Session API,您可以获得此SID(安全标识符)。

由于用户SID,您可以使用Microsoft.Win32.Registry.Users代替Microsoft.Win32.Registry.CurrentUser并打开正确的用户密钥。

您可以在stackoverflow上找到有关如何获取当前登录SID的几个主题,例如How to get a Unique ID for the current user's logon session in windows - c#

UPDATE:能够获取登录用户SID字符串的示例代码,它只能在系统会话中工作,因为它需要特殊权限SE_TCB_NAME。为简单起见,没有错误处理

static void Main(string[] args)
{
    Microsoft.Win32.RegistryKey mykey;
    mykey = Microsoft.Win32.Registry.Users.CreateSubKey(GetLoggedOnUserSID() + "\\Software\\Microsoft\\Windows\\Muhil Software");
    mykey.SetValue("Muhil", "TEST");
    mykey.Close();
}

enum TokenInformationClass
{
    TokenOwner = 4,
}

struct TokenOwner
{
    public IntPtr Owner;
}

[DllImport("advapi32.dll", EntryPoint = "GetTokenInformation", SetLastError = true)]
static extern bool GetTokenInformation(
    IntPtr tokenHandle,
    TokenInformationClass tokenInformationClass,
    IntPtr tokenInformation,
    int tokenInformationLength,
    out int ReturnLength);

[DllImport("kernel32.dll")]
private static extern UInt32 WTSGetActiveConsoleSessionId();

[DllImport("wtsapi32.dll", SetLastError = true)]
static extern bool WTSQueryUserToken(UInt32 sessionId, out IntPtr Token);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool ConvertSidToStringSid(IntPtr sid, [In, Out, MarshalAs(UnmanagedType.LPTStr)] ref string pStringSid);

static string GetLoggedOnUserSID()
{
    IntPtr tokenOwnerPtr;
    int tokenSize;
    IntPtr hToken;

    // Get a token from the logged on session
    // !!! this line will only work within the SYSTEM session !!!
    WTSQueryUserToken(WTSGetActiveConsoleSessionId(), out hToken); 

    // Get the size required to host a SID
    GetTokenInformation(hToken, TokenInformationClass.TokenOwner, IntPtr.Zero, 0, out tokenSize);
    tokenOwnerPtr = Marshal.AllocHGlobal(tokenSize);

    // Get the SID structure within the TokenOwner class
    GetTokenInformation(hToken, TokenInformationClass.TokenOwner, tokenOwnerPtr, tokenSize, out tokenSize);
    TokenOwner tokenOwner = (TokenOwner)Marshal.PtrToStructure(tokenOwnerPtr, typeof(TokenOwner));

    // Convert the SID into a string
    string strSID = "";
    ConvertSidToStringSid(tokenOwner.Owner, ref strSID);
    Marshal.FreeHGlobal(tokenOwnerPtr);
    return strSID;        
}