Other Managed Code Samples
Use the following managed code samples to set permissions and to create a user account.
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);
}
}
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();
}
}