user412272
user412272

Reputation: 21

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?

Upvotes: 0

Views: 1648

Answers (1)

VinayC
VinayC

Reputation: 49165

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

Upvotes: 1

Related Questions