Как добавить пользователя в Active directory - C#
Формулировка задачи:
Здравствуйте. Подскажите пожалуйста как можно добавить нового юзера в Active directory программным способом на C# . Блин чето ничего не могу придумать
Решение задачи: «Как добавить пользователя в Active directory»
textual
Листинг программы
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
namespace Psilon.AD
{
public static class AccountManagementExtensions
{
private const string UserNotFoundMsg = "User doesn't exists and cannot be enabled or disabled";
public static DirectoryEntry AsDirectoryEntry(this Principal principal)
{
return principal.GetUnderlyingObject() as DirectoryEntry;
}
public static void Delete(this UserPrincipal user)
{
EnsuresUserExists(user);
user.Delete();
}
public static object ReadAttribute(this UserPrincipal user, string attributeName)
{
EnsuresUserExists(user);
var entry = user.AsDirectoryEntry();
return entry.Properties[attributeName].Value;
}
public static T ReadAttribute<T>(this UserPrincipal user, string attributeName)
{
return (T) ReadAttribute(user, attributeName);
}
public static void UpdateAttribute(this UserPrincipal user, string attributeName, object value)
{
DirectoryEntry entry = user.AsDirectoryEntry();
object oldValue = entry.Properties[attributeName].Value;
entry.Properties[attributeName].Value = value;
try
{
entry.CommitChanges();
}
catch
{
entry.Properties[attributeName].Value = oldValue;
entry.CommitChanges();
throw;
}
}
public static void UpdateAttributes(this UserPrincipal user, params KeyValuePair<string, object>[] attributes)
{
var entry = user.AsDirectoryEntry();
foreach (var pair in attributes)
{
entry.Properties[pair.Key].Value = pair.Value;
}
entry.CommitChanges();
}
public static void Enable(this UserPrincipal user)
{
user.ChangeAccessibility(true);
}
public static void Disable(this UserPrincipal user)
{
user.ChangeAccessibility(false);
}
public static void ChangeAccessibility(this UserPrincipal user, bool value)
{
if (user.Enabled == value)
return;
user.Enabled = value;
user.Save();
}
// ReSharper disable once UnusedParameter.Local
private static void EnsuresUserExists(this UserPrincipal user)
{
if (user == null)
{
throw new ActiveDirectoryObjectNotFoundException(UserNotFoundMsg, typeof(UserPrincipal), null);
}
}
}
}