How to get the current application pool user in IIS when using impersonate=true?

To revert to the app pool user in managed code you can do the following:

using (WindowsIdentity.Impersonate(IntPtr.Zero)) 
{
   //This code executes under app pool user
}

Found a solution.

Using RevertToSelf you can strip the impersonation from a thread. In IIS this equates to the App Pool user.

Some doco

http://www.pinvoke.net/default.aspx/advapi32.reverttoself

http://msdn.microsoft.com/en-us/library/aa379317%28VS.85%29.aspx

And the code

    [DllImport("advapi32.dll", SetLastError = true)]
    static extern bool RevertToSelf();

    private static WindowsIdentity GetAppPoolIdentity()
    {
        WindowsIdentity identity = null;
        Win32Exception win32Exception = null;
        var thread = new Thread(o =>
                        {
                            if (!RevertToSelf())
                            {
                                var win32error = Marshal.GetLastWin32Error();
                                win32Exception = new Win32Exception(win32error);
                            }

                            identity = WindowsIdentity.GetCurrent();
                        });
        thread.Start();
        thread.Join();
        if (win32Exception != null)
        {
            throw win32Exception;
        }
        return identity;
    }