Question : Getting Microsoft.Win32.RegistryKe<wbr />y from PROFILEINFO.hProfile - from PInvoke to .Net

Hi,
I have a basic c#.net application that under certain circumstances need to impersonate another user and access their registry hive.
I have the impersonation and profile loading working fine using the following sequence:

(PInvoke) LogonUser
(PInvoke) LoadUserProfile
(.Net) WindowsIdentity.Impersonate()

I have a PROFILEINFO struct with a valid hProfile handle from the LoadUserProfile call. The documentation stated that this is a key handle to the user's registry hive.
Now obviously I could continue using revolting PInvoke calls to read and manipulate the registry using this handle, BUT..

What I really need is to be able to use the Microsoft.Win32 .net classes to do the manipulation. This is because I have to call a sealed .net assembly to do some work for me and IT needs a RegistryKey class.

So.. is there a way to get from my IntPtr registry 'handle' to a RegistryKey, or is there any other way to access the impersonated users registry hive using the .net classes?

Obviously I've tried just accessing Registry.CurrentUser after impersonation but I believe this still corresponds to the user under which the process started and so I am denied access.

Your help is appreciated!

Answer : Getting Microsoft.Win32.RegistryKe<wbr />y from PROFILEINFO.hProfile - from PInvoke to .Net

An easier way would be to use the APIs to load/unload the user's registry hive.   After that,  you can use the normal .Net classes to read/write the mounted hive.

Here is an example:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
    'LONG RegLoadKey(
    '  HKEY hKey,
    '  LPCTSTR lpSubKey,
    '  LPCTSTR lpFile
    ');
    Private Declare Auto Function RegLoadKey Lib "advapi32.dll" ( _
        ByVal hKey As IntPtr, _
        ByVal lpSubKey As String, _
        ByVal lpFile As String _
    ) As Integer
 
    'LONG RegUnLoadKey(
    '  HKEY hKey,
    '  LPCTSTR lpSubKey
    ');
    Private Declare Auto Function RegUnLoadKey Lib "advapi32.dll" ( _
        ByVal hKey As IntPtr, _
        ByVal lpSubKey As String _
    ) As Integer
 
    Public Sub LoadKey(ByVal key As RegistryKey, ByVal MountPoint As String, ByVal HivePath As String)
        Dim ret As Integer
        ret = RegLoadKey(key.hKey, MountPoint, HivePath)
        If ret <> 0 Then
            Throw New Win32Exception(ret)
        End If
    End Sub
 
    Public Sub UnLoadKey(ByVal Key As RegistryKey, ByVal MountPoint As String)
        Dim ret As Integer
        ret = RegUnLoadKey(Key.hKey, MountPoint)
        If ret <> 0 Then
            Throw New Win32Exception(ret)
        End If
    End Sub
Random Solutions  
 
programming4us programming4us