using System; using static Vanara.PInvoke.AdvApi32; using Vanara.PInvoke; using System.Runtime.InteropServices; using System.Security.AccessControl; namespace Vanara.Extensions { /// Extension methods for native and .NET access control objects. public static class AccessExtension { /// Converts a PSECURITY_DESCRIPTOR to a byte array. /// The security descriptor. /// The byte array of the PSECURITY_DESCRIPTOR. public static byte[] ToByteArray(this PSECURITY_DESCRIPTOR securityDescriptor) { var sdLength = GetSecurityDescriptorLength(securityDescriptor); var buffer = new byte[sdLength]; Marshal.Copy((IntPtr)securityDescriptor, buffer, 0, (int)sdLength); return buffer; } /// Converts a PSECURITY_DESCRIPTOR to a managed RawSecurityDescriptor. /// The security descriptor. /// The RawSecurityDescriptor. public static RawSecurityDescriptor ToManaged(this PSECURITY_DESCRIPTOR securityDescriptor) => new RawSecurityDescriptor(securityDescriptor.ToByteArray(), 0); /// Converts a RawSecurityDescriptor to a native safe handle. /// The RawSecurityDescriptor. /// A native safe handle for PSECURITY_DESCRIPTOR. public static SafePSECURITY_DESCRIPTOR ToNative(this RawSecurityDescriptor rawSD) => new SafePSECURITY_DESCRIPTOR(rawSD.ToByteArray()); /// Converts a RawSecurityDescriptor to a byte array. /// The RawSecurityDescriptor. /// A byte array. public static byte[] ToByteArray(this RawSecurityDescriptor rawSD) { var buffer = new byte[rawSD.BinaryLength]; rawSD.GetBinaryForm(buffer, 0); return buffer; } } }