using System; using System.Collections; using System.DirectoryServices; using System.Runtime.InteropServices; namespace SergeyHomyuk.LocalManagement { public static class LocalUtility { // Создание пользователя: public static void CreateLocalUser(string login, string fullName, string password) { var root = new DirectoryEntry(string.Format("WinNT://{0},computer", Environment.MachineName)); using (var user = root.Children.Add(login, "user")) { user.Properties["FullName"].Value = fullName; user.Invoke("SetPassword", new object[] { password }); user.CommitChanges(); } } // Создание группы: public static void CreateLocalGroup(string name, string description) { var root = new DirectoryEntry(string.Format("WinNT://{0},computer", Environment.MachineName)); using (var group = root.Children.Add(name, "group")) { group.Invoke("Put", new object[] { "description", description }); group.CommitChanges(); } } // Добавление пользователя в группу: public static void AddLocalUserToLocalGroup(string userName, string groupName) { string groupPath = string.Format("WinNT://{0}/{1},group", Environment.MachineName, groupName); string userPath = string.Format("WinNT://{0}/{1},user", Environment.MachineName, userName); var root = new DirectoryEntry(groupPath); root.Invoke("Add", new object[] { userPath }); root.CommitChanges(); } // Проверка, существует ли группа с заданным именем: public static bool IsLocalGroupExists(string name) { var root = new DirectoryEntry(string.Format("WinNT://{0},computer", Environment.MachineName)); try { root.Children.Find(name, "group"); return true; } catch (COMException e) { if (e.ErrorCode == -2147022676) return false; throw; } } // Проверка, является ли пользователь членом группы: public static bool IsUserInLocalGroup(string userName, string groupName) { var root = new DirectoryEntry(string.Format("WinNT://{0},computer", Environment.MachineName)); root = root.Children.Find(userName, "user"); var groups = root.Invoke("groups"); foreach (var group in (IEnumerable)groups) { var groupEntry = new DirectoryEntry(group); if (string.Equals(groupEntry.Name, groupName, StringComparison.CurrentCultureIgnoreCase)) return true; } return false; } } }