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
精彩评论