如何将“IIS AppPool \ DefaultAppPool”添加到组中?

时间:2015-08-13 03:23:11

标签: c# windows

我正在使用以下方式将用户添加到群组中:

// 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();
    }
}

UserPrincipal.FindByIdentityIIS AppPool\DefaultAppPool一起返回null,即使它适用于NT Service\w32timeAdministrator。使用lusrmgr.msc,用户可以在不添加的情况下添加,但我无法使用UserPrincipalGroupPrincipalPrincipal来吸引用户。

如何为Principal获取IIS AppPool\DefaultAppPool或以其他方式将其添加到本地群组?

1 个答案:

答案 0 :(得分:1)

您可以往返于SID以获得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;
    }
}