简体   繁体   中英

Adding network service account to a windows built-in user group in c#

I am trying to add network service account to a built in security group using the following code:

DirectoryEntry de = new DirectoryEntry("WinNT://" + System.Environment.MachineName);                 
DirectoryEntry deGroup = de.Children.Find( groupName, "group");   >> here groupname = <some builtin group>
DirectoryEntry usr = de.Children.Find(accountName,”user”); >> here accountname = NT AUTHORITY\NETWORK SERVICE
deGroup.Invoke("Add", new object[] { usr.Path });
deGroup.CommitChanges();

The highlighted throws an exception “The user name could not be found”. What am I missing? How can I add network service to a builtin-group?

If you are using .NET 3.5 or later then have a look at System.DirectoryServices.AccountManagement . These classes are far easy to work with. For example,

PrincipalContext pc = new PrincipalContext(ContextType.Domain);
var user = UserPrincipal.FindByIdentity(pc, "johndoe");
var group = GroupPrincipal.FindByIdentity(oPrincipalContext, "some group name");
group.Members.Add(user);
group.Save();

Note that for machine accounts (user or groups), you need to use ContextType.Machine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM