NtCreateFile - NtDoc

Native API online documentation, based on the System Informer (formerly Process Hacker) phnt headers
#ifndef _NTIOAPI_H

//
// System calls
//

/**
 * The NtCreateFile routine creates a new file or directory, or opens an existing file, device, directory, or volume.
 *
 * \param[out] FileHandle Pointer to a variable that receives a handle to the pipe.
 * \param[in] DesiredAccess The requested access to the object.
 * \param[in] ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that contains the object attributes, including pipe name.
 * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation.
 * \param[in] AllocationSize The initial allocation size in bytes for the file. Specify a non-zero value to eliminate disk fragmentation, since the file system pre-allocates the file using a contiguous block.
 * \param[in] FileAttributes The file attributes. Explicitly specified attributes are applied only when the file is created, superseded, or, in some cases, overwritten.
 * \param[in] ShareAccess The type of share access that the caller would like to use in the file.
 * \param[in] CreateDisposition Specifies how the file should be handled when the file already exists.
 * \param[in] CreateOptions Specifies the options to be applied when creating or opening the file.
 * \param[in] EaBuffer Pointer to an EA buffer used to pass extended attributes.
 * \param[in] EaLength Length of the EA buffer.
 * \return NTSTATUS Successful or errant status.
 * \sa https://learn.microsoft.com/en-us/windows/win32/api/Winternl/nf-winternl-ntcreatefile
 */
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateFile(
    _Out_ PHANDLE FileHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _In_ PCOBJECT_ATTRIBUTES ObjectAttributes,
    _Out_ PIO_STATUS_BLOCK IoStatusBlock,
    _In_opt_ PLARGE_INTEGER AllocationSize,
    _In_ ULONG FileAttributes,
    _In_ ULONG ShareAccess,
    _In_ ULONG CreateDisposition,
    _In_ ULONG CreateOptions,
    _In_reads_bytes_opt_(EaLength) PVOID EaBuffer,
    _In_ ULONG EaLength
    );

#endif

View code on GitHub
#ifndef _NTZWAPI_H

NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateFile(
    _Out_ PHANDLE FileHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _In_ PCOBJECT_ATTRIBUTES ObjectAttributes,
    _Out_ PIO_STATUS_BLOCK IoStatusBlock,
    _In_opt_ PLARGE_INTEGER AllocationSize,
    _In_ ULONG FileAttributes,
    _In_ ULONG ShareAccess,
    _In_ ULONG CreateDisposition,
    _In_ ULONG CreateOptions,
    _In_reads_bytes_opt_(EaLength) PVOID EaBuffer,
    _In_ ULONG EaLength
    );

#endif

View code on GitHub
// ntifs.h

__kernel_entry NTSYSCALLAPI NTSTATUS NtCreateFile(
  [out]          PHANDLE            FileHandle,
  [in]           ACCESS_MASK        DesiredAccess,
  [in]           POBJECT_ATTRIBUTES ObjectAttributes,
  [out]          PIO_STATUS_BLOCK   IoStatusBlock,
  [in, optional] PLARGE_INTEGER     AllocationSize,
  [in]           ULONG              FileAttributes,
  [in]           ULONG              ShareAccess,
  [in]           ULONG              CreateDisposition,
  [in]           ULONG              CreateOptions,
  [in, optional] PVOID              EaBuffer,
  [in]           ULONG              EaLength
);
View the official Windows Driver Kit DDI reference
// wdm.h

NTSYSAPI NTSTATUS ZwCreateFile(
  [out]          PHANDLE            FileHandle,
  [in]           ACCESS_MASK        DesiredAccess,
  [in]           POBJECT_ATTRIBUTES ObjectAttributes,
  [out]          PIO_STATUS_BLOCK   IoStatusBlock,
  [in, optional] PLARGE_INTEGER     AllocationSize,
  [in]           ULONG              FileAttributes,
  [in]           ULONG              ShareAccess,
  [in]           ULONG              CreateDisposition,
  [in]           ULONG              CreateOptions,
  [in, optional] PVOID              EaBuffer,
  [in]           ULONG              EaLength
);
View the official Windows Driver Kit DDI reference
// winternl.h

__kernel_entry NTSTATUS NtCreateFile(
  [out]          PHANDLE            FileHandle,
  [in]           ACCESS_MASK        DesiredAccess,
  [in]           POBJECT_ATTRIBUTES ObjectAttributes,
  [out]          PIO_STATUS_BLOCK   IoStatusBlock,
  [in, optional] PLARGE_INTEGER     AllocationSize,
  [in]           ULONG              FileAttributes,
  [in]           ULONG              ShareAccess,
  [in]           ULONG              CreateDisposition,
  [in]           ULONG              CreateOptions,
  [in]           PVOID              EaBuffer,
  [in]           ULONG              EaLength
);
View the official Win32 API reference

NtDoc

No description available.

Windows Driver Kit DDI reference (nf-ntifs-ntcreatefile)

NtCreateFile function

Description

The NtCreateFile routine creates a new file or opens an existing file.

Parameters

FileHandle [out]

A pointer to a HANDLE variable that receives a handle to the file.

DesiredAccess [in]

Specifies an ACCESS_MASK value that determines the requested access to the object.

In addition to the standard access rights that are defined for all types of objects, the caller can specify any of the following specific access rights; that is, rights that are specific to files.

ACCESS_MASK flag Allows caller to do this
FILE_READ_DATA Read data from the file.
FILE_READ_ATTRIBUTES Read the attributes of the file. For more information, see the description of the FileAttributes parameter.
FILE_READ_EA Read the extended attributes (EAs) of the file. This flag is irrelevant for device and intermediate drivers.
FILE_WRITE_DATA Write data to the file.
FILE_WRITE_ATTRIBUTES Write the attributes of the file. For more information, see the description of the FileAttributes parameter.
FILE_WRITE_EA Change the extended attributes (EAs) of the file. This flag is irrelevant for device and intermediate drivers.
FILE_APPEND_DATA Append data to the file.
FILE_EXECUTE Use system paging I/O to read data from the file into memory. This flag is irrelevant for device and intermediate drivers.

[!NOTE] Do not specify FILE_READ_DATA, FILE_WRITE_DATA, FILE_APPEND_DATA, or FILE_EXECUTE when you create or open a directory.

The caller can also specify the following generic access rights (rights that apply to all object types, where the meaning of each generic access right is specific to the object type). Generic access rights for file objects correspond to specific access rights as shown in the following table. (Note that "correspond" means "maps to" and does not mean that the value of the generic right is "equal to" the value of the bitwise OR of its specific rights mapping). The I/O manager defines the actual mapping.

Generic access right Maps to these specific access rights
GENERIC_READ STANDARD_RIGHTS_READ, FILE_READ_DATA, FILE_READ_ATTRIBUTES, FILE_READ_EA, and SYNCHRONIZE
GENERIC_WRITE STANDARD_RIGHTS_WRITE, FILE_WRITE_DATA, FILE_WRITE_ATTRIBUTES, FILE_WRITE_EA, FILE_APPEND_DATA, and SYNCHRONIZE
GENERIC_EXECUTE STANDARD_RIGHTS_EXECUTE, FILE_EXECUTE, FILE_READ_ATTRIBUTES, and SYNCHRONIZE. This value is irrelevant for device and intermediate drivers.
GENERIC_ALL FILE_ALL_ACCESS

[!NOTE] Generic access rights can only be specified for a file; they cannot be specified for a directory.

Some CreateOptions flags require that certain access flags be set in DesiredAccess when NtCreateFile is called. See the CreateOptions parameter for these details.

For example, if you specify GENERIC_READ for a file object, the routine maps this value to the FILE_GENERIC_READ bitmask of specific access rights. In the preceding table, the specific access rights that are listed for GENERIC_READ correspond to (but are not equal to) the access flags that are contained in the FILE_GENERIC_READ bitmask.

If the file is actually a directory, the caller can also specify the following generic access rights.

DesiredAccess flag Allows caller to do this
FILE_LIST_DIRECTORY List the files in the directory.
FILE_TRAVERSE Traverse the directory, in other words, include the directory in the path of a file.

For more information about access rights, see ACCESS_MASK and Access Rights.

ObjectAttributes [in]

A pointer to an OBJECT_ATTRIBUTES structure that specifies the object name and other attributes. Use InitializeObjectAttributes to initialize this structure. If the caller is not running in a system thread context, it must set the OBJ_KERNEL_HANDLE attribute when it calls InitializeObjectAttributes.

IoStatusBlock [out]

A pointer to an IO_STATUS_BLOCK structure that receives the final completion status and other information about the requested operation. In particular, the Information member receives one of the following values:

AllocationSize [in, optional]

A pointer to a LARGE_INTEGER that contains the initial allocation size, in bytes, for a file that is created or overwritten. If AllocationSize is NULL, no allocation size is specified. If no file is created or overwritten, AllocationSize is ignored.

FileAttributes [in]

Specifies one or more FILE_ATTRIBUTE_XXX flags, which represent the file attributes to set if you create or overwrite a file. The caller usually specifies FILE_ATTRIBUTE_NORMAL, which sets the default attributes. For a list of valid FILE_ATTRIBUTE_XXX flags, see the CreateFile routine in the Microsoft Windows SDK documentation. If no file is created or overwritten, FileAttributes is ignored.

ShareAccess [in]

Type of share access, which is specified as zero or any combination of the following flags.

ShareAccess flag Allows other threads to do this
FILE_SHARE_READ Read the file
FILE_SHARE_WRITE Write the file
FILE_SHARE_DELETE Delete the file

Device and intermediate drivers usually set ShareAccess to zero, which gives the caller exclusive access to the open file.

CreateDisposition [in]

Specifies the action to perform if the file does or does not exist. CreateDisposition can be one of the values in the following table.

CreateDisposition value Action if file exists Action if file does not exist
FILE_SUPERSEDE Replace the file. Create the file.
FILE_CREATE Return an error. Create the file.
FILE_OPEN Open the file. Return an error.
FILE_OPEN_IF Open the file. Create the file.
FILE_OVERWRITE Open the file, and overwrite it. Return an error.
FILE_OVERWRITE_IF Open the file, and overwrite it. Create the file.

CreateOptions [in]

Specifies the options to apply when the driver creates or opens the file. Use one or more of the flags in the following table.

CreateOptions flag Meaning
FILE_DIRECTORY_FILE (0x00000001) The file is a directory. Compatible CreateOptions flags are FILE_SYNCHRONOUS_IO_ALERT, FILE_SYNCHRONOUS_IO_NONALERT, FILE_WRITE_THROUGH, FILE_OPEN_FOR_BACKUP_INTENT, and FILE_OPEN_BY_FILE_ID. The CreateDisposition parameter must be set to FILE_CREATE, FILE_OPEN, or FILE_OPEN_IF.
FILE_WRITE_THROUGH (0x00000002) System services, file-system drivers, and drivers that write data to the file must actually transfer the data to the file before any requested write operation is considered complete.
FILE_SEQUENTIAL_ONLY (0x00000004) All access to the file will be sequential.
FILE_NO_INTERMEDIATE_BUFFERING (0x00000008) The file cannot be cached or buffered in a driver's internal buffers. This flag is incompatible with the DesiredAccess parameter's FILE_APPEND_DATA flag.
FILE_SYNCHRONOUS_IO_ALERT (0x00000010) All operations on the file are performed synchronously. Any wait on behalf of the caller is subject to premature termination from alerts. This flag also causes the I/O system to maintain the file-position pointer. If this flag is set, the SYNCHRONIZE flag must be set in the DesiredAccess parameter.
FILE_SYNCHRONOUS_IO_NONALERT (0x00000020) All operations on the file are performed synchronously. Waits in the system that synchronize I/O queuing and completion are not subject to alerts. This flag also causes the I/O system to maintain the file-position context. If this flag is set, the SYNCHRONIZE flag must be set in the DesiredAccess parameter.
FILE_NON_DIRECTORY_FILE (0x00000040) The file is not a directory. The file object to open can represent a data file; a logical, virtual, or physical device; or a volume. Starting in Windows 11, version 24H2, NTFS now honors this flag when opening a $INDEX_ALLOCATION attribute.
FILE_CREATE_TREE_CONNECTION (0x00000080) Create a tree connection for this file in order to open it over the network. This flag is not used by device and intermediate drivers.
FILE_COMPLETE_IF_OPLOCKED (0x00000100) Complete this operation immediately with an alternate success code of STATUS_OPLOCK_BREAK_IN_PROGRESS if the target file is oplocked, rather than blocking the caller's thread. If the file is oplocked, another caller already has access to the file. This flag is not used by device and intermediate drivers.
FILE_NO_EA_KNOWLEDGE (0x00000200) If the extended attributes (EAs) for an existing file being opened indicate that the caller must understand EAs to properly interpret the file, NtCreateFile should return an error. This flag is irrelevant for device and intermediate drivers.
FILE_OPEN_REMOTE_INSTANCE (0x00000400) Reserved for system use; do not use.
FILE_RANDOM_ACCESS (0x00000800) Access to the file can be random, so no sequential read-ahead operations should be performed by file-system drivers or by the system.
FILE_DELETE_ON_CLOSE (0x00001000) The system deletes the file when the last handle to the file is passed to NtClose. If this flag is set, the DELETE flag must be set in the DesiredAccess parameter.
FILE_OPEN_BY_FILE_ID (0x00002000) The file name that is specified by the ObjectAttributes parameter includes a binary 8-byte or 16-byte file reference number or object ID for the file, depending on the file system. Optionally, a device name followed by a backslash character may proceed these binary values. See Remarks for additional details and an example.
FILE_OPEN_FOR_BACKUP_INTENT (0x00004000) The file is being opened for backup intent. Therefore, the system should check for certain access rights and grant the caller the appropriate access to the file—before checking the DesiredAccess parameter against the file's security descriptor. This flag not used by device and intermediate drivers.
FILE_NO_COMPRESSION (0x00008000) Suppress inheritance of FILE_ATTRIBUTE_COMPRESSED from the parent directory. This allows creation of a non-compressed file in a directory that is marked compressed.
FILE_OPEN_REQUIRING_OPLOCK (0x00010000) The file is being opened and an opportunistic lock (oplock) on the file is being requested as a single atomic operation. The file system checks for oplocks before it performs the create operation, and will fail the create with a return code of STATUS_CANNOT_BREAK_OPLOCK if the result would be to break an existing oplock. This flag is available starting with Windows 7 and Windows Server 2008 R2.
FILE_DISALLOW_EXCLUSIVE (0x00020000) When opening an existing file, if FILE_SHARE_READ is not specified and file system access checks would not grant the caller write access to the file, fail this open with STATUS_ACCESS_DENIED. This was default behavior prior to Windows 7. This flag is available starting with Windows 7 and Windows Server 2008 R2.
FILE_SESSION_AWARE (0x00040000) The client opening the file or device is session aware and per session access is validated if necessary. This flag is available starting with Windows 8.
FILE_RESERVE_OPFILTER (0x00100000) This flag allows an application to request a Filter opportunistic lock (oplock) to prevent other applications from getting share violations. If there are already open handles, the create request will fail with STATUS_OPLOCK_NOT_GRANTED. For more information, see the following Remarks section.
FILE_OPEN_REPARSE_POINT (0x00200000) Open a file with a reparse point and bypass normal reparse point processing for the file. For more information, see the following Remarks section.
FILE_OPEN_NO_RECALL (0x00400000) Instructs any filters that perform offline storage or virtualization to not recall the contents of the file as a result of this open.
FILE_OPEN_FOR_FREE_SPACE_QUERY (0x00800000) This flag instructs the file system to capture the user associated with the calling thread. Any subsequent calls to FltQueryVolumeInformation or ZwQueryVolumeInformationFile using the returned handle will assume the captured user, rather than the calling user at the time, for purposes of computing the free space available to the caller. This applies to the following FsInformationClass values: FileFsSizeInformation, FileFsFullSizeInformation, and FileFsFullSizeInformationEx.
FILE_CONTAINS_EXTENDED_CREATE_INFORMATION (0x10000000) Interpret the EaBuffer parameter as an instance of EXTENDED_CREATE_INFORMATION. This flag is available starting in Windows 11, version 22H2.

EaBuffer [in, optional]

For device and intermediate drivers, this parameter must be a NULL pointer.

EaLength [in]

For device and intermediate drivers, this parameter must be zero.

Return value

NtCreateFile returns STATUS_SUCCESS on success or an appropriate NTSTATUS error code on failure. In the latter case, the caller can determine the cause of the failure by checking the IoStatusBlock parameter.

[!NOTE] NtCreateFile might return STATUS_FILE_LOCK_CONFLICT as the return value or in the Status member of the IO_STATUS_BLOCK structure that is pointed to by the IoStatusBlock parameter. This would occur only if the NTFS log file is full, and an error occurs while NtCreateFile tries to handle this situation.

Remarks

NtCreateFile supplies a handle that the caller can use to manipulate a file's data, or the file object's state and attributes. For more information, see Using Files in a Driver.

Once the handle pointed to by FileHandle is no longer in use, the driver must call NtClose to close it.

If the caller is not running in a system thread context, it must ensure that any handles it creates are private handles. Otherwise, the handle can be accessed by the process in whose context the driver is running. For more information, see Object Handles.

There are two alternate ways to specify the name of the file to be created or opened with NtCreateFile:

Setting certain flags in the DesiredAccess parameter results in the following effects:

The ShareAccess parameter determines whether separate threads can access the same file, possibly simultaneously. Provided that both callers have the appropriate access privileges, the file can be successfully opened and shared. If the original caller of NtCreateFile does not specify FILE_SHARE_READ, FILE_SHARE_WRITE, or FILE_SHARE_DELETE, no other caller can open the file—that is, the original caller is granted exclusive access.

To successfully open a shared file, the DesiredAccess flags must be compatible with the DesiredAccess and ShareAccess flags of all the previous open operations that have not yet been released through . That is, the DesiredAccess specified to NtCreateFile for a given file must not conflict with the accesses that other openers of the file have disallowed.

The CreateDisposition value FILE_SUPERSEDE requires that the caller have DELETE access to an existing file object. If so, a successful call to NtCreateFile with FILE_SUPERSEDE on an existing file effectively deletes that file, and then recreates it. This implies that, if the file has already been opened by another thread, it opened the file by specifying a ShareAccess parameter with the FILE_SHARE_DELETE flag set. Note that this type of disposition is consistent with the POSIX style of overwriting files.

The CreateDisposition values FILE_OVERWRITE_IF and FILE_SUPERSEDE are similar. If NtCreateFile is called with an existing file and either of these CreateDisposition values, the file will be replaced.

Overwriting a file is semantically equivalent to a supersede operation, except for the following:

The FILE_DIRECTORY_FILE CreateOptions value specifies that the file to be created or opened is a directory. When a directory file is created, the file system creates an appropriate structure on the disk to represent an empty directory for that particular file system's on-disk structure. If this option was specified and the given file to be opened is not a directory file, or if the caller specified an inconsistent CreateOptions or CreateDisposition value, the call to NtCreateFile will fail.

The FILE_NO_INTERMEDIATE_BUFFERING CreateOptions flag prevents the file system from performing any intermediate buffering on behalf of the caller. Specifying this flag places the following restrictions on the caller's parameters to other ZwXxxFile routines.

The FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT CreateOptions flags (which are mutually exclusive) specify that all I/O operations on the file will be synchronous, as long as the operations occur through the file object referred to by the returned FileHandle. All I/O on such a file is serialized across all threads using the returned handle. If either of these CreateOptions flags is set, the SYNCHRONIZE DesiredAccess flag must also be set to compel the I/O manager to use the file object as a synchronization object. In these cases, the I/O manager keeps track of the current file-position offset, which you can pass to NtReadFile and NtWriteFile. Call NtQueryInformationFile or NtSetInformationFile to get or set this position.

If the CreateOptions FILE_OPEN_REPARSE_POINT flag is not specified and NtCreateFile attempts to open a file with a reparse point, normal reparse point processing occurs for the file. If, on the other hand, the FILE_OPEN_REPARSE_POINT flag is specified, normal reparse processing does not occur and NtCreateFile attempts to directly open the reparse point file. In either case, if the open operation was successful, NtCreateFile returns STATUS_SUCCESS; otherwise, the routine returns an NTSTATUS error code. NtCreateFile never returns STATUS_REPARSE.

The CreateOptions FILE_OPEN_REQUIRING_OPLOCK flag eliminates the time between when you open the file and request an oplock that could potentially allow a third party to open the file and get a sharing violation. An application can use the FILE_OPEN_REQUIRING_OPLOCK flag on NtCreateFile and then request any oplock. This ensures that an oplock owner will be notified of any subsequent open request that causes a sharing violation.

In Windows 7, if other handles exist on the file when an application uses the FILE_OPEN_REQUIRING_OPLOCK flag, the create operation will fail with STATUS_OPLOCK_NOT_GRANTED. This restriction no longer exists starting with Windows 8.

If this create operation would break an oplock that already exists on the file, then setting the FILE_OPEN_REQUIRING_OPLOCK flag will cause the create operation to fail with STATUS_CANNOT_BREAK_OPLOCK. The existing oplock will not be broken by this create operation.

An application that uses the FILE_OPEN_REQUIRING_OPLOCK flag must request an oplock after this call succeeds, or all subsequent attempts to open the file will be blocked without the benefit of normal oplock processing. Similarly, if this call succeeds but the subsequent oplock request fails, an application that uses this flag must close its handle after it detects that the oplock request has failed. The application must not perform any other file system operation on the file before requesting the oplock (besides closing the file handle), otherwise a deadlock may occur.

[!NOTE] The FILE_OPEN_REQUIRING_OPLOCK flag is available in Windows 7, Windows Server 2008 R2 and later Windows operating systems. The Microsoft file systems that implement this flag in Windows 7 are NTFS, FAT, and exFAT.

The CreateOptions flag FILE_RESERVE_OPFILTER allows an application to request a Level 1, Batch, or Filter oplock to prevent other applications from getting share violations. However, FILE_RESERVE_OPFILTER is only practically useful for Filter oplocks. To use it, you must complete the following steps:

  1. Issue a create request with CreateOptions of FILE_RESERVE_OPFILTER, DesiredAccess of exactly FILE_READ_ATTRIBUTES, and ShareAccess of exactly FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE.
    • If there are already open handles, the create request fails with STATUS_OPLOCK_NOT_GRANTED, and the next requested oplock also fails.
    • If you open with more access or less sharing will also cause a failure of STATUS_OPLOCK_NOT_GRANTED.
  2. If the create request succeeds, request an oplock.
  3. Open another handle to the file to do I/O.

Step 3 makes this practical only for Filter oplocks. The handle opened in step 3 can have a DesiredAccess that contains a maximum of FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_DATA | FILE_READ_EA | FILE_EXECUTE | SYNCHRONIZE | READ_CONTROL and still not break a Filter oplock. However, any DesiredAccess greater than FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE will break a Level 1 or Batch oplock and make the FILE_RESERVE_OPFILTER flag useless for those oplock types.

NTFS is the only Microsoft file system that implements FILE_RESERVE_OPFILTER.

For the CreateOptions FILE_OPEN_BY_FILE_ID flag, an example device name will have the format:

\??\C:\<FileID>
\device\HardDiskVolume1\<ObjectID>

where FileID is 8 bytes and ObjectID is 16 bytes:

This number is assigned by and specific to the particular file system. Because the filename field will partly contain a binary blob, it is incorrect to assume that this is a valid Unicode string, and more importantly may not be a null terminated string.

Callers of NtCreateFile must be running at IRQL = PASSIVE_LEVEL and with special kernel APCs enabled.

[!NOTE] If the call to this function occurs in user mode, you should use the name "NtCreateFile" instead of "ZwCreateFile".

For calls from kernel-mode drivers, the Nt*Xxx* and Zw*Xxx* versions of a Windows Native System Services routine can behave differently in the way that they handle and interpret input parameters. For more information about the relationship between the Nt*Xxx* and Zw*Xxx* versions of a routine, see Using Nt and Zw Versions of the Native System Services Routines.

See also

ACCESS_MASK

DEVICE_OBJECT

EXTENDED_CREATE_INFORMATION

IO_STATUS_BLOCK

InitializeObjectAttributes

NtClose

NtOpenFile

NtQueryInformationFile

NtReadFile

NtSetInformationFile

NtWriteFile


Windows Driver Kit DDI reference (nf-wdm-zwcreatefile)

Description

The ZwCreateFile routine creates a new file or opens an existing file.

Parameters

FileHandle [out]

A pointer to a HANDLE variable that receives a handle to the file.

DesiredAccess [in]

Specifies an ACCESS_MASK value that determines the requested access to the object. In addition to the access rights that are defined for all types of objects, the caller can specify any of the following access rights, which are specific to files.

ACCESS_MASK flag Allows caller to do this
FILE_READ_DATA Read data from the file.
FILE_READ_ATTRIBUTES Read the attributes of the file. (For more information, see the description of the FileAttributes parameter.)
FILE_READ_EA Read the extended attributes (EAs) of the file. This flag is irrelevant for device and intermediate drivers.
FILE_WRITE_DATA Write data to the file.
FILE_WRITE_ATTRIBUTES Write the attributes of the file. (For more information, see the description of the FileAttributes parameter.)
FILE_WRITE_EA Change the extended attributes (EAs) of the file. This flag is irrelevant for device and intermediate drivers.
FILE_APPEND_DATA Append data to the file.
FILE_EXECUTE Use system paging I/O to read data from the file into memory. This flag is irrelevant for device and intermediate drivers.

Do not specify FILE_READ_DATA, FILE_WRITE_DATA, FILE_APPEND_DATA, or FILE_EXECUTE when you create or open a directory.

The caller can only specify a generic access right, GENERIC_XXX, for a file, not a directory. Generic access rights correspond to specific access rights as shown in the following table.

Generic access right Set of specific access rights
GENERIC_READ STANDARD_RIGHTS_READ, FILE_READ_DATA, FILE_READ_ATTRIBUTES, FILE_READ_EA, and SYNCHRONIZE.
GENERIC_WRITE STANDARD_RIGHTS_WRITE, FILE_WRITE_DATA, FILE_WRITE_ATTRIBUTES, FILE_WRITE_EA, FILE_APPEND_DATA, and SYNCHRONIZE.
GENERIC_EXECUTE STANDARD_RIGHTS_EXECUTE, FILE_EXECUTE, FILE_READ_ATTRIBUTES, and SYNCHRONIZE. This value is irrelevant for device and intermediate drivers.
GENERIC_ALL FILE_ALL_ACCESS.

For example, if you specify GENERIC_READ for a file object, the routine maps this value to the FILE_GENERIC_READ bitmask of specific access rights. In the preceding table, the specific access rights that are listed for GENERIC_READ correspond to the access flags that are contained in the FILE_GENERIC_READ bitmask.

If the file is actually a directory, the caller can also specify the following generic access rights.

DesiredAccess flag Allows caller to do this
FILE_LIST_DIRECTORY List the files in the directory.
FILE_TRAVERSE Traverse the directory, in other words, include the directory in the path of a file.

For more information about access rights, see ACCESS_MASK.

ObjectAttributes [in]

A pointer to an OBJECT_ATTRIBUTES structure that specifies the object name and other attributes. Use InitializeObjectAttributes to initialize this structure. If the caller is not running in a system thread context, it must set the OBJ_KERNEL_HANDLE attribute when it calls InitializeObjectAttributes.

IoStatusBlock [out]

A pointer to an IO_STATUS_BLOCK structure that receives the final completion status and other information about the requested operation. In particular, the Information member receives one of the following values:

AllocationSize [in, optional]

A pointer to a LARGE_INTEGER that contains the initial allocation size, in bytes, for a file that is created or overwritten. If AllocationSize is NULL, no allocation size is specified. If no file is created or overwritten, AllocationSize is ignored.

FileAttributes [in]

Specifies one or more FILE_ATTRIBUTE_XXX flags, which represent the file attributes to set if you create or overwrite a file. The caller usually specifies FILE_ATTRIBUTE_NORMAL, which sets the default attributes. For a list of valid FILE_ATTRIBUTE_XXX flags, see the CreateFile routine. If no file is created or overwritten, FileAttributes is ignored.

ShareAccess [in]

Type of share access, which is specified as zero or any combination of the following flags.

ShareAccess flag Allows other threads to do this
FILE_SHARE_READ Read the file
FILE_SHARE_WRITE Write the file
FILE_SHARE_DELETE Delete the file

Device and intermediate drivers usually set ShareAccess to zero, which gives the caller exclusive access to the open file.

CreateDisposition [in]

Specifies the action to perform if the file does or does not exist. CreateDisposition can be one of the values in the following table.

CreateDisposition value Action if file exists Action if file does not exist
FILE_SUPERSEDE Replace the file. Create the file.
FILE_CREATE Return an error. Create the file.
FILE_OPEN Open the file. Return an error.
FILE_OPEN_IF Open the file. Create the file.
FILE_OVERWRITE Open the file, and overwrite it. Return an error.
FILE_OVERWRITE_IF Open the file, and overwrite it. Create the file.

CreateOptions [in]

Specifies the options to apply when the driver creates or opens the file. Use one or more of the flags in the following table.

CreateOptions flag Meaning
FILE_DIRECTORY_FILE The file is a directory. Compatible CreateOptions flags are FILE_SYNCHRONOUS_IO_ALERT, FILE_SYNCHRONOUS_IO_NONALERT, FILE_WRITE_THROUGH, FILE_OPEN_FOR_BACKUP_INTENT, and FILE_OPEN_BY_FILE_ID. The CreateDisposition parameter must be set to FILE_CREATE, FILE_OPEN, or FILE_OPEN_IF.
FILE_NON_DIRECTORY_FILE The file is not a directory. The file object to open can represent a data file; a logical, virtual, or physical device; or a volume.
FILE_WRITE_THROUGH System services, file-system drivers, and drivers that write data to the file must actually transfer the data to the file before any requested write operation is considered complete.
FILE_SEQUENTIAL_ONLY All access to the file will be sequential.
FILE_RANDOM_ACCESS Access to the file can be random, so no sequential read-ahead operations should be performed by file-system drivers or by the system.
FILE_NO_INTERMEDIATE_BUFFERING The file cannot be cached or buffered in a driver's internal buffers. This flag is incompatible with the DesiredAccess parameter's FILE_APPEND_DATA flag.
FILE_SYNCHRONOUS_IO_ALERT All operations on the file are performed synchronously. Any wait on behalf of the caller is subject to premature termination from alerts. This flag also causes the I/O system to maintain the file-position pointer. If this flag is set, the SYNCHRONIZE flag must be set in the DesiredAccess parameter.
FILE_SYNCHRONOUS_IO_NONALERT All operations on the file are performed synchronously. Waits in the system that synchronize I/O queuing and completion are not subject to alerts. This flag also causes the I/O system to maintain the file-position context. If this flag is set, the SYNCHRONIZE flag must be set in the DesiredAccess parameter.
FILE_CREATE_TREE_CONNECTION Create a tree connection for this file in order to open it over the network. This flag is not used by device and intermediate drivers.
FILE_COMPLETE_IF_OPLOCKED Complete this operation immediately with an alternate success code of STATUS_OPLOCK_BREAK_IN_PROGRESS if the target file is opportunistic locked (oplock), rather than blocking the caller's thread. If the file is oplocked, another caller already has access to the file. This flag is not used by device and intermediate drivers. For information about oplock, see Opportunistic Locks.
FILE_NO_EA_KNOWLEDGE If the extended attributes (EAs) for an existing file being opened indicate that the caller must understand EAs to properly interpret the file, ZwCreateFile should return an error. This flag is irrelevant for device and intermediate drivers.
FILE_OPEN_REPARSE_POINT Open a file with a reparse point and bypass normal reparse point processing for the file. For more information, see the following Remarks section. For information about reparse point, see Reparse Points.
FILE_DELETE_ON_CLOSE The system deletes the file when the last handle to the file is passed to ZwClose. If this flag is set, the DELETE flag must be set in the DesiredAccess parameter.
FILE_OPEN_BY_FILE_ID The file name that is specified by the ObjectAttributes parameter includes a binary 8-byte or 16-byte file reference number or object ID for the file, depending on the file system as shown below. Optionally, a device name followed by a backslash character may proceed these binary values. For example, a device name will have the following format:

\??\C:\FileID
\device\HardDiskVolume1\ObjectID

where FileID is 8 bytes and ObjectID is 16 bytes.

On NTFS, this can be an 8-byte or 16-byte reference number or object ID. A 16-byte reference number is the same as an 8-byte number padded with zeros.

On ReFS, this can be an 8-byte or 16-byte reference number. A 16-byte number is not related to an 8-byte number. Object IDs are not supported.

The FAT, ExFAT, UDFS, and CDFS file systems do not support this flag.

This number is assigned by and specific to the particular file system.

Because the filename field will partly contain a binary blob, it is incorrect to assume that this is a valid Unicode string, and more importantly may not be a null terminated string.
FILE_OPEN_FOR_BACKUP_INTENT The file is being opened for backup intent. Therefore, the system should check for certain access rights and grant the caller the appropriate access to the file—before checking the DesiredAccess parameter against the file's security descriptor. This flag not used by device and intermediate drivers.
FILE_RESERVE_OPFILTER This flag allows an application to request a Filter opportunistic lock (oplock) to prevent other applications from getting share violations. If there are already open handles, the create request will fail with STATUS_OPLOCK_NOT_GRANTED. For more information, see the following Remarks section. For information about oplock, see Opportunistic Locks.
FILE_OPEN_REQUIRING_OPLOCK The file is being opened and an opportunistic lock (oplock) on the file is being requested as a single atomic operation. The file system checks for oplocks before it performs the create operation, and will fail the create with a return code of STATUS_CANNOT_BREAK_OPLOCK if the result would be to break an existing oplock.

The FILE_OPEN_REQUIRING_OPLOCK flag is available in Windows 7, Windows Server 2008 R2 and later Windows operating systems.
FILE_SESSION_AWARE The client opening the file or device is session aware and per session access is validated if necessary.

The FILE_SESSION_AWARE flag is available starting withWindows 8.

EaBuffer [in, optional]

For device and intermediate drivers, this parameter must be a NULL pointer.

EaLength [in]

For device and intermediate drivers, this parameter must be zero.

Return value

ZwCreateFile returns STATUS_SUCCESS on success or an appropriate NTSTATUS error code on failure. In the latter case, the caller can determine the cause of the failure by checking the IoStatusBlock parameter.

ZwCreateFile might return STATUS_FILE_LOCK_CONFLICT as the return value or in the Status member of the IO_STATUS_BLOCK structure that is pointed to by the IoStatusBlock parameter. This would occur only if the NTFS log file is full, and an error occurs while ZwCreateFile tries to handle this situation.

Remarks

ZwCreateFile supplies a handle that the caller can use to manipulate a file's data, or the file object's state and attributes. For more information, see Using Files in a Driver.

Once the handle pointed to by FileHandle is no longer in use, the driver must call ZwClose to close it.

If the caller is not running in a system thread context, it must ensure that any handles it creates are private handles. Otherwise, the handle can be accessed by the process in whose context the driver is running. For more information, see Object Handles.

There are two alternate ways to specify the name of the file to be created or opened with ZwCreateFile:

  1. As a fully qualified pathname, supplied in the ObjectName member of the input ObjectAttributes.

  2. As pathname relative to the directory file represented by the handle in the RootDirectory member of the input ObjectAttributes.

Setting certain flags in the DesiredAccess parameter results in the following effects:

The ShareAccess parameter determines whether separate threads can access the same file, possibly simultaneously. Provided that both callers have the appropriate access privileges, the file can be successfully opened and shared. If the original caller of ZwCreateFile does not specify FILE_SHARE_READ, FILE_SHARE_WRITE, or FILE_SHARE_DELETE, no other caller can open the file—that is, the original caller is granted exclusive access.

To successfully open a shared file, the DesiredAccess flags must be compatible with the DesiredAccess and ShareAccess flags of all the previous open operations that have not yet been released through . That is, the DesiredAccess specified to ZwCreateFile for a given file must not conflict with the accesses that other openers of the file have disallowed.

The CreateDisposition value FILE_SUPERSEDE requires that the caller have DELETE access to an existing file object. If so, a successful call to ZwCreateFile with FILE_SUPERSEDE on an existing file effectively deletes that file, and then recreates it. This implies that, if the file has already been opened by another thread, it opened the file by specifying a ShareAccess parameter with the FILE_SHARE_DELETE flag set. Note that this type of disposition is consistent with the POSIX style of overwriting files.

The CreateDisposition values FILE_OVERWRITE_IF and FILE_SUPERSEDE are similar. If ZwCreateFile is called with an existing file and either of these CreateDisposition values, the file will be replaced.

Overwriting a file is semantically equivalent to a supersede operation, except for the following:

The FILE_DIRECTORY_FILE CreateOptions value specifies that the file to be created or opened is a directory. When a directory file is created, the file system creates an appropriate structure on the disk to represent an empty directory for that particular file system's on-disk structure. If this option was specified and the given file to be opened is not a directory file, or if the caller specified an inconsistent CreateOptions or CreateDisposition value, the call to ZwCreateFile will fail.

The FILE_NO_INTERMEDIATE_BUFFERING CreateOptions flag prevents the file system from performing any intermediate buffering on behalf of the caller. Specifying this flag places the following restrictions on the caller's parameters to other ZwXxxFile routines:

The FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT CreateOptions flags, which are mutually exclusive as their names suggest, specify that all I/O operations on the file will be synchronous—as long as they occur through the file object referred to by the returned FileHandle. All I/O on such a file is serialized across all threads using the returned handle. If either of these CreateOptions flags is set, the SYNCHRONIZE DesiredAccess flag must also be set—to compel the I/O manager to use the file object as a synchronization object. In these cases, the I/O manager keeps track of the current file-position offset, which you can pass to ZwReadFile and ZwWriteFile. Call ZwQueryInformationFile or ZwSetInformationFile to get or set this position.

If the CreateOptions FILE_OPEN_REPARSE_POINT flag is not specified and ZwCreateFile attempts to open a file with a reparse point, normal reparse point processing occurs for the file. If, on the other hand, the FILE_OPEN_REPARSE_POINT flag is specified, normal reparse processing does not occur and ZwCreateFile attempts to directly open the reparse point file. In either case, if the open operation was successful, ZwCreateFile returns STATUS_SUCCESS; otherwise, the routine returns an NTSTATUS error code. ZwCreateFile never returns STATUS_REPARSE.

The CreateOptions FILE_OPEN_REQUIRING_OPLOCK flag eliminates the time between when you open the file and request an oplock that could potentially allow a third party to open the file and get a sharing violation. An application can use the FILE_OPEN_REQUIRING_OPLOCK flag on ZwCreateFile and then request any oplock. This ensures that an oplock owner will be notified of any subsequent open request that causes a sharing violation.

In Windows 7, if other handles exist on the file when an application uses the FILE_OPEN_REQUIRING_OPLOCK flag, the create operation will fail with STATUS_OPLOCK_NOT_GRANTED. This restriction no longer exists starting with Windows 8.

If this create operation would break an oplock that already exists on the file, then setting the FILE_OPEN_REQUIRING_OPLOCK flag will cause the create operation to fail with STATUS_CANNOT_BREAK_OPLOCK. The existing oplock will not be broken by this create operation.

An application that uses the FILE_OPEN_REQUIRING_OPLOCK flag must request an oplock after this call succeeds, or all subsequent attempts to open the file will be blocked without the benefit of normal oplock processing. Similarly, if this call succeeds but the subsequent oplock request fails, an application that uses this flag must close its handle after it detects that the oplock request has failed.

The FILE_OPEN_REQUIRING_OPLOCK flag is available in Windows 7, Windows Server 2008 R2 and later Windows operating systems. The Microsoft file systems that implement this flag in Windows 7 are NTFS, FAT, and exFAT.

The CreateOptions flag FILE_RESERVE_OPFILTER allows an application to request a Level 1, Batch, or Filter oplock to prevent other applications from getting share violations. However, FILE_RESERVE_OPFILTER is only practically useful for Filter oplocks. To use it, you must complete the following steps:

  1. Issue a create request with CreateOptions of FILE_RESERVE_OPFILTER, DesiredAccess of exactly FILE_READ_ATTRIBUTES, and ShareAccess of exactly FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE.

    • If there are already open handles, the create request fails with STATUS_OPLOCK_NOT_GRANTED, and the next requested oplock also fails.

    • If you open with more access or less sharing will also cause a failure of STATUS_OPLOCK_NOT_GRANTED.

  2. If the create request succeeds, request an oplock.

  3. Open another handle to the file to do I/O.

Step three makes this practical only for Filter oplocks. The handle opened in step 3 can have a DesiredAccess that contains a maximum of FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_DATA | FILE_READ_EA | FILE_EXECUTE | SYNCHRONIZE | READ_CONTROL and still not break a Filter oplock. However, any DesiredAccess greater than FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE will break a Level 1 or Batch oplock and make the FILE_RESERVE_OPFILTER flag useless for those oplock types.

NTFS is the only Microsoft file system that implements FILE_RESERVE_OPFILTER.

Callers of ZwCreateFile must be running at IRQL = PASSIVE_LEVEL and with special kernel APCs enabled.

If the call to this function occurs in user mode, you should use the name "NtCreateFile" instead of "ZwCreateFile".

For calls from kernel-mode drivers, the Nt*Xxx* and Zw*Xxx* versions of a Windows Native System Services routine can behave differently in the way that they handle and interpret input parameters. For more information about the relationship between the Nt*Xxx* and Zw*Xxx* versions of a routine, see Using Nt and Zw Versions of the Native System Services Routines.

See also

ACCESS_MASK

DEVICE_OBJECT

IO_STATUS_BLOCK

InitializeObjectAttributes

Using Nt and Zw Versions of the Native System Services Routines

ZwClose

ZwOpenFile

ZwQueryInformationFile

ZwReadFile

ZwSetInformationFile

ZwWriteFile

Opportunistic Locks

Reparse Points


Win32 API reference (nf-winternl-ntcreatefile)

NtCreateFile function

Description

Creates a new file or directory, or opens an existing file, device, directory, or volume.

This function is the user-mode equivalent to the ZwCreateFile function documented in the Windows Driver Kit (WDK).

Parameters

FileHandle [out]

A pointer to a variable that receives the file handle if the call is successful.

DesiredAccess [in]

The ACCESS_MASK value that expresses the type of access that the caller requires to the file or directory. The set of system-defined DesiredAccess flags determines the following specific access rights for file objects.

Value Meaning
DELETE The file can be deleted.
FILE_READ_DATA Data can be read from the file.
FILE_READ_ATTRIBUTES FileAttributes flags, described later, can be read.
FILE_READ_EA Extended attributes associated with the file can be read. This flag is irrelevant to device and intermediate drivers.
READ_CONTROL The access control list (ACL) and ownership information associated with the file can be read.
FILE_WRITE_DATA Data can be written to the file.
FILE_WRITE_ATTRIBUTES FileAttributes flags can be written.
FILE_WRITE_EA Extended attributes (EAs) associated with the file can be written. This flag is irrelevant to device and intermediate drivers.
FILE_APPEND_DATA Data can be appended to the file.
WRITE_DAC The discretionary access control list (DACL) associated with the file can be written.
WRITE_OWNER Ownership information associated with the file can be written.
SYNCHRONIZE The returned FileHandle can be waited on to synchronize with the completion of an I/O operation. If FileHandle was not opened for synchronous I/O, this value is ignored.
FILE_EXECUTE Data can be read into memory from the file using system paging I/O. This flag is irrelevant for device and intermediate drivers.

Do not specify FILE_READ_DATA, FILE_WRITE_DATA, FILE_APPEND_DATA, or FILE_EXECUTE when you create or open a directory.

Callers of NtCreateFile can specify one or a combination of the following, possibly using a bitwise-OR with additional compatible flags from the preceding DesiredAccess flags list, for any file object that does not represent a directory file.

Value Meaning
FILE_GENERIC_READ `STANDARD_RIGHTS_READ FILE_READ_DATA FILE_READ_ATTRIBUTES FILE_READ_EA SYNCHRONIZE`
FILE_GENERIC_WRITE `STANDARD_RIGHTS_WRITE FILE_WRITE_DATA FILE_WRITE_ATTRIBUTES FILE_WRITE_EA FILE_APPEND_DATA SYNCHRONIZE`
FILE_GENERIC_EXECUTE `STANDARD_RIGHTS_EXECUTE FILE_READ_ATTRIBUTES FILE_EXECUTE SYNCHRONIZE`

The FILE_GENERIC_EXECUTE value is irrelevant for device and intermediate drivers.

The STANDARD_RIGHTS_XXX are predefined system values used to enforce security on system objects.

To open or create a directory file, as also indicated with the CreateOptions parameter, callers of NtCreateFile can specify one or a combination of the following, possibly using a bitwise-OR with one or more compatible flags from the preceding DesiredAccess flags list.

Value Meaning
FILE_LIST_DIRECTORY Files in the directory can be listed.
FILE_TRAVERSE The directory can be traversed: that is, it can be part of the pathname of a file.

ObjectAttributes [in]

A pointer to a structure already initialized with InitializeObjectAttributes. Members of this structure for a file object include the following.

Value Meaning
ULONG Length Specifies the number of bytes of ObjectAttributes data supplied. This value must be at least sizeof(OBJECT_ATTRIBUTES).
HANDLE RootDirectory Optionally specifies a handle to a directory obtained by a preceding call to NtCreateFile. If this value is NULL, the ObjectName member must be a fully qualified file specification that includes the full path to the target file. If this value is non-NULL, the ObjectName member specifies a file name relative to this directory.
PUNICODE_STRING ObjectName Points to a buffered Unicode string that names the file to be created or opened. This value must be a fully qualified file specification or the name of a device object, unless it is the name of a file relative to the directory specified by RootDirectory. For example, \Device\Floppy1\myfile.dat or \??\B:\myfile.dat could be the fully qualified file specification, provided that the floppy driver and overlying file system are already loaded. For more information, see File Names, Paths, and Namespaces.
ULONG Attributes Is a set of flags that controls the file object attributes. This value can be zero or OBJ_CASE_INSENSITIVE, which indicates that name-lookup code should ignore the case of the ObjectName member rather than performing an exact-match search. The value OBJ_INHERIT is irrelevant to device and intermediate drivers.
PSECURITY_DESCRIPTOR SecurityDescriptor Optionally specifies a security descriptor to be applied to a file. ACLs specified by such a security descriptor are applied to the file only when it is created. If the value is NULL when a file is created, the ACL placed on the file is file-system-dependent; most file systems propagate some part of such an ACL from the parent directory file combined with the caller's default ACL. Device and intermediate drivers can set this member to NULL.
PSECURITY_QUALITY_OF_SERVICE SecurityQualityOfService Specifies the access rights a server should be given to the client's security context. This value is non-NULL only when a connection to a protected server is established, allowing the caller to control which parts of the caller's security context are made available to the server and whether the server is allowed to impersonate the caller.

IoStatusBlock [out]

A pointer to a variable that receives the final completion status and information about the requested operation. On return from NtCreateFile, the Information member contains one of the following values:

AllocationSize [in, optional]

The initial allocation size in bytes for the file. A nonzero value has no effect unless the file is being created, overwritten, or superseded.

FileAttributes [in]

The file attributes. Explicitly specified attributes are applied only when the file is created, superseded, or, in some cases, overwritten. By default, this value is a FILE_ATTRIBUTE_NORMAL, which can be overridden by an ORed combination of one or more FILE_ATTRIBUTE_xxxx flags, which are defined in Wdm.h and NtDdk.h. For a list of flags that can be used with NtCreateFile, see CreateFile.

ShareAccess [in]

The type of share access that the caller would like to use in the file, as zero, or as one or a combination of the following values.

Value Meaning
FILE_SHARE_READ The file can be opened for read access by other threads' calls to NtCreateFile.
FILE_SHARE_WRITE The file can be opened for write access by other threads' calls to NtCreateFile.
FILE_SHARE_DELETE The file can be opened for delete access by other threads' calls to NtCreateFile.

For more information, see the Windows SDK.

CreateDisposition [in]

Specifies what to do, depending on whether the file already exists, as one of the following values.

Value Meaning
FILE_SUPERSEDE If the file already exists, replace it with the given file. If it does not, create the given file.
FILE_CREATE If the file already exists, fail the request and do not create or open the given file. If it does not, create the given file.
FILE_OPEN If the file already exists, open it instead of creating a new file. If it does not, fail the request and do not create a new file.
FILE_OPEN_IF If the file already exists, open it. If it does not, create the given file.
FILE_OVERWRITE If the file already exists, open it and overwrite it. If it does not, fail the request.
FILE_OVERWRITE_IF If the file already exists, open it and overwrite it. If it does not, create the given file.

CreateOptions [in]

The options to be applied when creating or opening the file, as a compatible combination of the following flags.

Value Meaning
FILE_DIRECTORY_FILE The file being created or opened is a directory file. With this flag, the CreateDisposition parameter must be set to FILE_CREATE, FILE_OPEN, or FILE_OPEN_IF. With this flag, other compatible CreateOptions flags include only the following: FILE_SYNCHRONOUS_IO_ALERT, FILE_SYNCHRONOUS_IO _NONALERT, FILE_WRITE_THROUGH, FILE_OPEN_FOR_BACKUP_INTENT, and FILE_OPEN_BY_FILE_ID.
FILE_NON_DIRECTORY_FILE The file being opened must not be a directory file or this call fails. The file object being opened can represent a data file, a logical, virtual, or physical device, or a volume.
FILE_WRITE_THROUGH Applications that write data to the file must actually transfer the data into the file before any requested write operation is considered complete. This flag is automatically set if the CreateOptions flag FILE_NO_INTERMEDIATE _BUFFERING is set.
FILE_SEQUENTIAL_ONLY All accesses to the file are sequential.
FILE_RANDOM_ACCESS Accesses to the file can be random, so no sequential read-ahead operations should be performed on the file by FSDs or the system.
FILE_NO_INTERMEDIATE_BUFFERING The file cannot be cached or buffered in a driver's internal buffers. This flag is incompatible with the DesiredAccess FILE_APPEND_DATA flag.
FILE_SYNCHRONOUS_IO_ALERT All operations on the file are performed synchronously. Any wait on behalf of the caller is subject to premature termination from alerts. This flag also causes the I/O system to maintain the file position context. If this flag is set, the DesiredAccess SYNCHRONIZE flag also must be set.
FILE_SYNCHRONOUS_IO_NONALERT All operations on the file are performed synchronously. Waits in the system to synchronize I/O queuing and completion are not subject to alerts. This flag also causes the I/O system to maintain the file position context. If this flag is set, the DesiredAccess SYNCHRONIZE flag also must be set.
FILE_CREATE_TREE_CONNECTION Create a tree connection for this file in order to open it over the network. This flag is not used by device and intermediate drivers.
FILE_NO_EA_KNOWLEDGE If the extended attributes on an existing file being opened indicate that the caller must understand EAs to properly interpret the file, fail this request because the caller does not understand how to deal with EAs. This flag is irrelevant for device and intermediate drivers.
FILE_OPEN_REPARSE_POINT Open a file with a reparse point and bypass normal reparse point processing for the file. For more information, see the Remarks section.
FILE_DELETE_ON_CLOSE Delete the file when the last handle to it is passed to NtClose. If this flag is set, the DELETE flag must be set in the DesiredAccess parameter.
FILE_OPEN_BY_FILE_ID The file name that is specified by the ObjectAttributes parameter includes the 8-byte file reference number for the file. This number is assigned by and specific to the particular file system. If the file is a reparse point, the file name will also include the name of a device. Note that the FAT file system does not support this flag. This flag is not used by device and intermediate drivers.
FILE_OPEN_FOR_BACKUP_INTENT The file is being opened for backup intent. Therefore, the system should check for certain access rights and grant the caller the appropriate access to the file before checking the DesiredAccess parameter against the file's security descriptor. This flag not used by device and intermediate drivers.
FILE_RESERVE_OPFILTER This flag allows an application to request a filter opportunistic lock to prevent other applications from getting share violations. If there are already open handles, the create request will fail with STATUS_OPLOCK_NOT_GRANTED. For more information, see the Remarks section.
FILE_OPEN_REQUIRING_OPLOCK The file is being opened and an opportunistic lock on the file is being requested as a single atomic operation. The file system checks for oplocks before it performs the create operation and will fail the create with a return code of STATUS_CANNOT_BREAK_OPLOCK if the result would be to break an existing oplock. For more information, see the Remarks section.

Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This flag is not supported.

This flag is supported on the following file systems: NTFS, FAT, and exFAT.
FILE_COMPLETE_IF_OPLOCKED Complete this operation immediately with an alternate success code of STATUS_OPLOCK_BREAK_IN_PROGRESS if the target file is oplocked, rather than blocking the caller's thread. If the file is oplocked, another caller already has access to the file. This flag is not used by device and intermediate drivers.

EaBuffer [in]

Pointer to an EA buffer used to pass extended attributes.

Note Some file systems may not support EA buffers.

EaLength [in]

Length of the EA buffer.

Return value

NtCreateFile returns either STATUS_SUCCESS or an appropriate error status. If it returns an error status, the caller can find more information about the cause of the failure by checking the IoStatusBlock. To simplify this check, an application can use the NT_SUCCESS, NT_ERROR, and NT_WARNING macros.

Remarks

The handle, given by NtCreateFile, can be used by subsequent calls to manipulate data within the file or the file object's state or attributes.

There are two alternate ways to specify the name of the file to be created or opened with NtCreateFile:

Certain DesiredAccess flags and combinations of flags have the following effects:

The ShareAccess parameter determines whether separate threads can access the same file, possibly simultaneously. Provided that both file openers have the privilege to access a file in the specified manner, the file can be successfully opened and shared. If the original caller of NtCreateFile does not specify FILE_SHARE_READ, FILE_SHARE_WRITE, or FILE_SHARE_DELETE, no other open operations can be performed on the file; that is, the original caller is given exclusive access to the file.

For a shared file to be successfully opened, the requested DesiredAccess parameter to the file must be compatible with both the DesiredAccess and ShareAccess specifications of all preceding opens that have not yet been released with NtClose. That is, the DesiredAccess parameter specified to NtCreateFile for a given file must not conflict with the accesses that other openers of the file have disallowed.

The CreateDisposition value FILE_SUPERSEDE requires that the caller have DELETE access to an existing file object. If so, a successful call to NtCreateFile with FILE_SUPERSEDE on an existing file effectively deletes that file, and then re-creates it. This implies that, if the file has already been opened by another thread, it opened the file by specifying a ShareAccess parameter with the FILE_SHARE_DELETE flag set.

Note that this type of disposition is consistent with the POSIX style of overwriting files. The CreateDisposition values FILE_OVERWRITE_IF and FILE_SUPERSEDE are similar. If ZwCreateFile is called with an existing file and either of these CreateDisposition values, the file is replaced.

Overwriting a file is semantically equivalent to a supersede operation, except for the following:

The CreateOptions FILE_DIRECTORY_FILE value specifies that the file to be created or opened is a directory file. When a directory file is created, the file system creates an appropriate structure on the disk to represent an empty directory for that particular file system's on-disk structure. If this option was specified and the given file to be opened is not a directory file, or if the caller specified an inconsistent CreateOptions or CreateDisposition value, the call to NtCreateFile fails.

The CreateOptions FILE_NO_INTERMEDIATE_BUFFERING flag prevents the file system from performing any intermediate buffering on behalf of the caller. Specifying this value places certain restrictions on the caller's parameters to other NtXXXFile routines, including the following:

The CreateOptions FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT flags, which are mutually exclusive as their names suggest, specify that all I/O operations on the file are to be synchronous as long as they occur through the file object referred to by the returned FileHandle. All I/O on such a file is serialized across all threads using the returned handle. With either of these CreateOptions, the DesiredAccess SYNCHRONIZE flag must be set so that the I/O Manager uses the file object as a synchronization object. With either of these CreateOptions set, the I/O Manager maintains the "file position context" for the file object, an internal, current file position offset. This offset can be used in calls to NtReadFile and NtWriteFile. Its position also can be queried or set with NtQueryInformationFile and NtSetInformationFile.

If the CreateOptions parameter specifies the FILE_OPEN_REPARSE_POINT flag and NtCreateFile opens a file with a reparse point, normal reparse processing does not occur and NtCreateFile attempts to directly open the reparse point file. If the FILE_OPEN_REPARSE_POINT flag is not specified, normal reparse point processing occurs for the file. In either case, if the open operation was successful, NtCreateFile returns STATUS_SUCCESS; otherwise, an error code. The NtCreateFile function never returns STATUS_REPARSE.

The CreateOptions parameter's FILE_OPEN_REQUIRING_OPLOCK flag eliminates the time between when you open the file and request an oplock that could potentially allow a third party to open the file, which would cause a sharing violation. An application can use the FILE_OPEN_REQUIRING_OPLOCK flag with NtCreateFile and then request any oplock. This ensures that an oplock owner will be notified of any subsequent open request that causes a sharing violation.

In Windows 7, if other handles exist on the file when an application uses this flag, the create operation will fail with STATUS_OPLOCK_NOT_GRANTED. This restriction no longer exists starting with Windows 8.

If this create operation would break an oplock that already exists on the file, then setting the FILE_OPEN_REQUIRING_OPLOCK flag will cause the create operation to fail with STATUS_CANNOT_BREAK_OPLOCK. The existing oplock will not be broken by this create operation.

An application that uses the FILE_OPEN_REQUIRING_OPLOCK flag must request an oplock on the file after this call succeeds, or all subsequent attempts to open the file will be blocked without the benefit of normal oplock processing. Similarly, if this call succeeds but the subsequent oplock request fails, an application that uses this flag must close its handle after it detects that the oplock request has failed. The application must not perform any other file system operation on the file before requsting the oplock (besides closing the file handle), otherwise a deadlock may occur.

Note The FILE_OPEN_REQUIRING_OPLOCK flag is available in Windows 7, Windows Server 2008 R2 and later operating systems for the following file systems: NTFS, FAT, and exFAT.

The CreateOptions parameter's FILE_RESERVE_OPFILTER flag allows an application to request a Level 1, Batch, or Filter oplock to prevent other applications from getting share violations. However, in practical terms, the FILE_RESERVE_OPFILTER is useful only for filter oplocks. To use it, you must complete the following steps:

  1. Issue a create request with CreateOptions of FILE_RESERVE_OPFILTER, DesiredAccess of exactly FILE_READ_ATTRIBUTES, and ShareAccess of exactly (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE). Possible failures are as follows:
    • If there are already open handles, the create request fails with STATUS_OPLOCK_NOT_GRANTED, and the next requested oplock also fails.
    • If you open with more access than FILE_READ_ATTRIBUTES or less sharing than (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), the request fails with STATUS_OPLOCK_NOT_GRANTED.
  2. If the create request succeeds, request an oplock.
  3. Open another handle to the file to do I/O.

Step three makes this practical only for filter oplocks. The handle opened in step three can have a DesiredAccess that contains a maximum of (FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_DATA | FILE_READ_EA | FILE_EXECUTE | SYNCHRONIZE | READ_CONTROL) and still not break a filter oplock. However, any DesiredAccess greater than (FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE) will break a Level 1 or Batch oplock and make the FILE_RESERVE_OPFILTER flag useless for those oplock types.

NTFS is the only Microsoft file system that implements FILE_RESERVE_OPFILTER.

For more information on oplocks, see Opportunistic Locks.

Note that the WDK header file NtDef.h is necessary for many constant definitions. You can also use the LoadLibrary and GetProcAddress functions to dynamically link to NtDll.dll.


NTinternals.net (undocumented.ntinternals.net)

This function is documented in Windows Driver Kit here and here.


(Available also in 2000 DDK.)

FileHandle

Result of call - HANDLE to File Object.

DesiredAccess

Access mask based on definitions in schema FILE_* from <WinNT.h>.

ObjectAttributes

Name of file to create (or open), optionally path in name string. You can also define root directory, security descriptor and attributes OBJ_CASE_INSENSITIVE and OBJ_INHERIT.

IoStatusBlock

Pointer to IO_STATUS_BLOCK structure, that receive final status of function call. Can be one of:

AllocationSize

File size after creation.

FileAttributes

Attributes for newly created file, as follows:

ShareAccess

Specifies share method for opened object. Can be set to zero or any combination of flags:

CreateDisposition

Specifies disposition how to create or open object and can be one of:

CreateOptions

Creation options.

EaBuffer

Buffer for Extended Attributes contains one or more of FILE_FULL_EA_INFORMATION structures.

EaLength

Length of EaBuffer.

Related Win32 API

Documented by

See also