Opening a Handle to a File
To open a handle to a file, perform the following steps:
Create an OBJECT_ATTRIBUTES structure, and call the InitializeObjectAttributes macro to initialize the structure. You specify the file's object name as the ObjectName parameter to InitializeObjectAttributes.
Open a handle to the file by passing the OBJECT_ATTRIBUTES structure to IoCreateFile, ZwCreateFile, or ZwOpenFile.
If the file does not exist, IoCreateFile and ZwCreateFile will create it, whereas ZwOpenFile will return STATUS_OBJECT_NAME_NOT_FOUND.
Note that drivers almost always use ZwCreateFile or ZwOpenFile rather than IoCreateFile.
When you call IoCreateFile, ZwCreateFile, or ZwOpenFile, the Windows executive creates a new file object to represent the file, and it provides an open handle to the object. This file object persists until you close all the open handles to it.
Whichever routine you call, you must pass the access rights you need as the DesiredAccess parameter. These rights must cover all the operations that your driver will perform. The following table lists these operations and the corresponding access right to request.
Operation | Required access right |
---|---|
Read from the file. |
FILE_READ_DATA or GENERIC_READ |
Write to the file. |
FILE_WRITE_DATA or GENERIC_WRITE |
Write only to the end of the file. |
FILE_APPEND_DATA |
Read the file's metadata, such as the file's creation time. |
FILE_READ_ATTRIBUTES or GENERIC_READ |
Write the file's metadata, such as the file's creation time. |
FILE_WRITE_ATTRIBUTES or GENERIC_WRITE |
For more information about the values available for DesiredAccess, see ZwCreateFile.