Desktop Functions:

   Smart Device Functions:

Show Recent Changes
Subscribe (RSS)
Misc. Pages
Helpful Tools
Suggested Reading
Website TODO List
Download Visual Studio Add-In

CreateDirectory (kernel32)

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:


    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,
        public IntPtr? pSecurityDescriptor = null;
        //internal unsafe byte* pSecurityDescriptor = null;
        internal int bInheritHandle = 0;
        public IntPtr lpSecurityDescriptor;


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:



Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

Access directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version