private List <TrustedDomain> DomainArrayToTrustedDomainList(NETLOGON_TRUSTED_DOMAIN_ARRAY trustedDomainArray) { List <TrustedDomain> output = new List <TrustedDomain>(); int size = Marshal.SizeOf(typeof(DS_DOMAIN_TRUSTSW)); for (int i = 0; i < trustedDomainArray.DomainCount; i++) { DS_DOMAIN_TRUSTSW trust = (DS_DOMAIN_TRUSTSW)Marshal.PtrToStructure(new IntPtr(trustedDomainArray.Domains.ToInt64() + size * i), typeof(DS_DOMAIN_TRUSTSW)); TrustedDomain domain = new TrustedDomain(); if (trust.DnsDomainName != IntPtr.Zero) { domain.DnsDomainName = Marshal.PtrToStringUni(trust.DnsDomainName); FreeMemory(trust.DnsDomainName); } if (trust.NetbiosDomainName != IntPtr.Zero) { domain.NetbiosDomainName = Marshal.PtrToStringUni(trust.NetbiosDomainName); FreeMemory(trust.NetbiosDomainName); } domain.Flags = (TrustedDomainFlag)trust.Flags; domain.ParentIndex = trust.ParentIndex; domain.TrustAttributes = trust.TrustAttributes; domain.TrustType = trust.TrustType; domain.DomainGuid = trust.DomainGuid; if (trust.DomainSid != IntPtr.Zero) { domain.DomainSid = new SecurityIdentifier(trust.DomainSid); FreeMemory(trust.DomainSid); } output.Add(domain); } FreeMemory(trustedDomainArray.Domains); return(output); }
public Int32 DsrEnumerateDomainTrusts(string server, int flag, out List <TrustedDomain> domains) { IntPtr result = IntPtr.Zero; domains = null; IntPtr intptrServer = Marshal.StringToHGlobalUni(server); NETLOGON_TRUSTED_DOMAIN_ARRAY output = new NETLOGON_TRUSTED_DOMAIN_ARRAY(); try { if (IntPtr.Size == 8) { result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(0), intptrServer, flag, ref output); } else { GCHandle handle = GCHandle.Alloc(output, GCHandleType.Pinned); IntPtr tempValuePointer = handle.AddrOfPinnedObject(); try { result = CallNdrClientCall2x86(0, intptrServer, new IntPtr((int)flag), tempValuePointer); // each pinvoke work on a copy of the arguments (without an out specifier) // get back the data output = (NETLOGON_TRUSTED_DOMAIN_ARRAY)Marshal.PtrToStructure(tempValuePointer, typeof(NETLOGON_TRUSTED_DOMAIN_ARRAY)); } finally { handle.Free(); } } } catch (SEHException) { return(Marshal.GetExceptionCode()); } finally { if (intptrServer != IntPtr.Zero) { Marshal.FreeHGlobal(intptrServer); } } domains = DomainArrayToTrustedDomainList(output); return((int)result.ToInt64()); }