Reputation: 22301
I am adding a user to a group using:
// reference System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
using (var context = new PrincipalContext(ContextType.Machine))
using (var group = GroupPrincipal.FindByIdentity(context, GroupName))
using (var user = UserPrincipal.FindByIdentity(context, Username))
{
if (group == null || user == null)
{
throw new InvalidOperationException(string.Format("User '{0}' or group '{1}' does not exist", Username, GroupName));
}
if (!group.Members.Contains(user))
{
group.Members.Add(user);
group.Save();
}
}
But UserPrincipal.FindByIdentity
returns null with IIS AppPool\DefaultAppPool
even though it works with NT Service\w32time
and Administrator
. Using lusrmgr.msc
, the user can be added without incedent, but I cannot use UserPrincipal
, GroupPrincipal
, or Principal
to get the user.
How can I get a Principal
for IIS AppPool\DefaultAppPool
or otherwise add it to a local group?
Upvotes: 0
Views: 975
Reputation: 22301
You can round-trip through a SID to get a Principal
:
private Principal GetUserPrincipal(PrincipalContext context, string name)
{
var nta = new NTAccount(name);
try
{
var sid = nta.Translate(typeof(SecurityIdentifier)).Value;
return Principal.FindByIdentity(context, IdentityType.Sid, sid);
}
catch (IdentityNotMappedException)
{
return null;
}
}
Upvotes: 1