Access CurrentUser Registry Key for Impersonated User - Compatibility with .NET 3.5

前端 未结 2 923
故里飘歌
故里飘歌 2021-01-07 02:21

I\'ve recently written an application that impersonate user account, get a handle to CURRENT_USER registry key (using PInvoke \"LoadUserProfile\" to retrieve ProfileInfo.hPr

2条回答
  •  执笔经年
    2021-01-07 03:09

    Wrote an Impersonation class I posted here to answer the same kind of question: Impersonate admin account to edit registry key not working (C#)

    To write to the key, you just do:

    string userName = "domain\user";
    string password = "whatever";
    string KEY_STR = "SomeSubKey\\ASubKeyToThat";
    
    WindowsImpersonationContext adminContext = Impersonation.getWic(userName, password);
    if (adminContext != null)
    {
        try
        {
           RegistryKey key = Registry.CurrentUser.OpenSubKey(KEY_STR, true);
           key.SetValue("State", 0x60001);
        }
        catch (Exception ex)
        {
            Console.Out.WriteLine("\nUnable to set registry value:\n\t" + ex.Message);
            Impersonation.endImpersonation();
            adminContext.Undo();
        }
        finally
        {
            Impersonation.endImpersonation();
            // The above line does this --            
            //if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle);
            adminContext.Undo();
        }
    }
    

    No handles or other fancy functions, other than to get the WindowsImpersonationContext needed. Didn't repost that part because it looks like you already know how to get the WIC.

提交回复
热议问题