Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


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

CreateDirectory (kernel32)
 
.
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

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 PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions