CreateDirectory (kernel32)
Last changed: WithLithum-112.101.111.191

.
Summary

C# Signature:

//If the value of SECURITY_ATTRIBUTES is NULL, the object is assigned the default security descriptor associated with the access token of the calling process
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool CreateDirectory(String path, SECURITY_ATTRIBUTES lpSecurityAttributes);

User-Defined Types:

SECURITY_ATTRIBUTES C#:

    [StructLayout(LayoutKind.Sequential)]
    public class SECURITY_ATTRIBUTES
    {
        internal int nLength = 0;
        // don't remove null, or it will fail to set the default ACL, making the folder inaccessible and non-removeable
        // unsafe is available if compile with /unsafe flag, https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs0227
        public IntPtr? pSecurityDescriptor = null;
        //or
        //internal unsafe byte* pSecurityDescriptor = null;
        internal int bInheritHandle = 0;
        public IntPtr lpSecurityDescriptor;
    }

Notes:

Please add some!

Tips & Tricks:

Don't don't remove null, or it will fail to set the default ACL, making the folder inaccessible and non-removeable.

'unsafe' variable types are available if compile with /unsafe flag, @errorhelp

Sample Code:

public static bool CreateFolder(string path)
{
    var lpSecurityAttributes = new SECURITY_ATTRIBUTES();
    var security = new System.Security.AccessControl.DirectorySecurity();
    lpSecurityAttributes.nLength = Marshal.SizeOf(lpSecurityAttributes);
    byte[] src = security.GetSecurityDescriptorBinaryForm();
    IntPtr dest = Marshal.AllocHGlobal(src.Length);
    Marshal.Copy(src, 0, dest, src.Length);
    lpSecurityAttributes.lpSecurityDescriptor = dest;
    return CreateDirectory(path, lpSecurityAttributes);
}

Alternative Managed API:

System.IO.Directory.CreateDirectory

Documentation