Search code examples
c#.netdllimportimpersonationadvapi32

Logoff after logonuser on C#


I use advapi32.dll's logonuser method to access data over our network.
I know it change the thread's user to the information i give it, but i was wondering if there's a way to reverse it.
I want to access the data and then return to the local user credentials.


Solution

  • Some time ago I created a small impersonator class.

    Basically you wrap your code to execute under another user simply inside a using block:

    using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
    {
       ...
    
       <code that executes under the new context>
    
       ...
    }
    

    Worked very well for my projects.