40

How do I get the identity of an appPool programmatically in C#? I want the application pool user and NOT the user who is currently logged in.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
p0enkie
  • 665
  • 2
  • 11
  • 22

3 Answers3

60

You could use System.Security.Principal.WindowsIdentity.GetCurrent().Name to identify the Identity in which the current application is running. This link provides a nice utility which displays the identity under which the aspx is run.

Ramesh
  • 13,043
  • 3
  • 52
  • 88
adt
  • 4,320
  • 5
  • 35
  • 54
  • If I change the appPool identity in the IIS Manager shouldn't System.Security.Principal.WindowsIdentity.GetCurrent().Name get the changed value? – p0enkie Apr 11 '12 at 12:23
  • 11
    Ok for someone out there that might be struggling, this is the code I used to get the username that started the AppPool (it's identity): ApplicationPool pool = serverManager.ApplicationPools["YoutAppPoolName"]; pool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser; string user = pool.ProcessModel.UserName; – p0enkie May 07 '12 at 06:47
  • 3
    @p0enkie what is `serverManager` ? – Kiquenet Dec 09 '15 at 11:29
  • It is present in C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll. var serverManager = new ServerManager(); – Steven Bone Dec 17 '15 at 13:03
9

You need to make a reference to Microsoft.Web.Administration (in Microsoft.Web.Administration.dll). Microsoft.Web.Administration.dll is located in C:\Windows\System32\inetsrv.

//Add this to your using statements:
using Microsoft.Web.Administration;

//You can get the App Pool identity like this:    
public string GetAppPoolIdentity(string appPoolName)
{
    var serverManager = new ServerManager();

    ApplicationPool appPool = serverManager.ApplicationPools[appPoolName];
    appPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
    return appPool.ProcessModel.UserName;            
}
Donal
  • 31,121
  • 10
  • 63
  • 72
  • I used this code and it returns blank string. What could be the reason? I have just programmatically created an application pool and I am using the same pool name that I just created. – devanalyst Feb 22 '21 at 16:33
3

Another possibility that seems to work OK for me and does not require installation of the Microsoft.Web.Administration package and its legion dependencies:

string appPoolUserIdentity = WindowsIdentity.GetCurrent().Name;

From forums.asp.net

Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67
  • Nice answer, but really the same suggestion as the accepted answer, isn't it? The [accepted answer](https://stackoverflow.com/a/10101417/1175496) says to use: `System.Security.Principal.WindowsIdentity.GetCurrent().Name` – Nate Anderson Jan 25 '22 at 19:17
  • It may equate to the same. I mentioned it because it seemed to be more simple to deploy without all the Using's. – Vanquished Wombat Jan 26 '22 at 09:11