using System; using System.Linq; using System.DirectoryServices.ActiveDirectory; using Vanara.Extensions.Reflection; using static Vanara.PInvoke.NTDSApi; namespace Vanara.Extensions { /// Extensions for AD objects (e.g. DomainController). public static class ActiveDirectoryExtension { /// /// Converts an array of directory service object names from one format to another. Name conversion enables client applications to /// map between the multiple names used to identify various directory service objects. For example, user objects can be identified /// by SAM account names (Domain\UserName), user principal name (UserName@Domain.com), or distinguished name. /// /// The instance to query. /// The names to convert. /// /// Contains one of the DS_NAME_FORMAT values that identifies the format of the output names. The DS_SID_OR_SID_HISTORY_NAME value /// is not supported. /// /// Contains one of the DS_NAME_FORMAT values that identifies the format of the input names. /// Contains one or more of the DS_NAME_FLAGS values used to determine how the name syntax will be cracked. /// The converted names. public static string[] CrackNames(this DomainController dc, string[] names, DS_NAME_FORMAT formatDesired = DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME, DS_NAME_FORMAT formatOffered = DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME, DS_NAME_FLAGS flags = DS_NAME_FLAGS.DS_NAME_NO_FLAGS) { lock (dc) using (var ds = dc.GetHandle()) return DsCrackNames(ds, names, formatDesired, formatOffered, flags).Select(r => r.pName).ToArray(); } /// Uses reflection to get the hiddent handle of a . /// The instance. /// A for the domain controller in . /// public static SafeDsHandle GetHandle(this DomainController dc) { var hDc = dc.GetPropertyValue("Handle", IntPtr.Zero); if (hDc == IntPtr.Zero) throw new InvalidOperationException(); return new SafeDsHandle(hDc); } } }