Edit

Share via


Other Managed Code Samples

by Walter Oliver

Introduction

Use the following managed code samples to set permissions and to create a user account.

Using the Code

Set Permissions

Use the following to set permissions on a folder using managed code .

Note

A reference to System.DirectoryServices.dll is required.

using System;
using System.IO;
using System.DirectoryServices;
using System.Security.AccessControl;
using System.Security.Principal;

class Program
{
    static void Main(string[] args)
    {
        String dir = @"e:\content";
        DirectorySecurity dirsec = Directory.GetAccessControl(dir);
        dirsec.SetAccessRuleProtection(true, false);
        foreach (AuthorizationRule rule in dirsec.GetAccessRules(true, true, typeof(NTAccount)))
        {
        dirsec.RemoveAccessRuleAll(new FileSystemAccessRule(rule.IdentityReference, FileSystemRights.FullControl, AccessControlType.Allow));
        }
    dirsec.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Administrators", FileSystemRights. FullControl,AccessControlType.Allow));
    dirsec.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Administrators", FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
    dirsec.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Administrators", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
    Directory.SetAccessControl(dir, dirsec);
    }
}

Create a User Account

Use the following to create a user account using managed code.

using System;
using System.DirectoryServices;
class Program
{
    static void Main(string[] args)
    {
        DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
        DirectoryEntry NewUser = AD.Children.Add("PoolID1", "user");
        NewUser.Invoke("SetPassword", new object[] { "PoolIDPwd1" });
        NewUser.Invoke("Put", new object[] { "Description", "AppPool Account" });
        NewUser.CommitChanges();
    }
}

Additional resources

Training

Module

Secure Windows Server user accounts - Training

Protect your Active Directory environment by securing user accounts to least privilege and placing them in the Protected Users group. Learn how to limit authentication scope and remediate potentially insecure accounts.

Certification

Microsoft Certified: Identity and Access Administrator Associate - Certifications

Demonstrate the features of Microsoft Entra ID to modernize identity solutions, implement hybrid solutions, and implement identity governance.