public static SecurityIdentifier GetLocalMachineAuthoritySid() { IntPtr pPolicyHandle = IntPtr.Zero; IntPtr pPolicyData = IntPtr.Zero; try { LsaObjectAttributes lsaObjectAttributes = new LsaObjectAttributes(); var result = LsaOpenPolicy(IntPtr.Zero, ref lsaObjectAttributes, LsaAccessPolicy.PolicyViewLocalInformation, out pPolicyHandle); if (result != 0) { result = LsaNtStatusToWinError(result); throw new DirectoryException("LsaOpenPolicy failed", new Win32Exception(result)); } result = LsaQueryInformationPolicy(pPolicyHandle, PolicyInformationClass.PolicyAccountDomainInformation, out pPolicyData); if (result != 0) { result = LsaNtStatusToWinError(result); throw new DirectoryException("LsaQueryInformationPolicy failed", new Win32Exception(result)); } PolicyAccountDomainInfo info = Marshal.PtrToStructure <PolicyAccountDomainInfo>(pPolicyData); return(new SecurityIdentifier(info.DomainSid)); } finally { if (pPolicyData != IntPtr.Zero) { LsaFreeMemory(pPolicyData); } if (pPolicyHandle != IntPtr.Zero) { LsaClose(pPolicyHandle); } } }
private static extern int LsaOpenPolicy(IntPtr pSystemName, ref LsaObjectAttributes objectAttributes, LsaAccessPolicy desiredAccess, out IntPtr pPolicyHandle);