Microsoft windows file objects

Creating a File Mapping Object

The first step in mapping a file is to open the file by calling the CreateFile function. To ensure that other processes cannot write to the portion of the file that is mapped, you should open the file with exclusive access. In addition, the file handle should remain open until the process no longer needs the file mapping object. An easy way to obtain exclusive access is to specify zero in the fdwShareMode parameter of CreateFile. The handle returned by CreateFile is used by the CreateFileMapping function to create a file mapping object.

The CreateFileMapping function returns a handle to the file mapping object. This handle will be used when creating a file view so that you can access the shared memory. When you call CreateFileMapping, you specify an object name, the number of bytes to be mapped from the file, and the read/write permission for the mapped memory. The first process that calls CreateFileMapping creates the file mapping object. Processes calling CreateFileMapping for an existing object receive a handle to the existing object. You can tell whether or not a successful call to CreateFileMapping created or opened the file mapping object by calling the GetLastError function. GetLastError returns NO_ERROR to the creating process and ERROR_ALREADY_EXISTS to subsequent processes.

The CreateFileMapping function fails if the access flags conflict with those specified when the CreateFile function opened the file. For example, to read and write to the file:

  • Specify the GENERIC_READ and GENERIC_WRITE values in the fdwAccess parameter of CreateFile.
  • Specify the PAGE_READWRITE value in the fdwProtect parameter of CreateFileMapping.

Creating a file mapping object does not commit physical memory, it only reserves it.

File Mapping Size

The size of the file mapping object is independent of the size of the file being mapped. However, if the file mapping object is larger than the file, the system expands the file before CreateFileMapping returns. If the file mapping object is smaller than the file, the system maps only the specified number of bytes from the file.

The dwMaximumSizeHigh and dwMaximumSizeLow parameters of CreateFileMapping allow you to specify the number of bytes to be mapped from the file:

When you do not want the size of the file to change (for example, when mapping read-only files), call CreateFileMapping and specify zero for both dwMaximumSizeHigh and dwMaximumSizeLow. Doing this creates a file mapping object that is exactly the same size as the file. Otherwise, you must calculate or estimate the size of the finished file because file mapping objects are static in size; once created, their size cannot be increased or decreased. An attempt to map a file with a length of zero in this manner fails with an error code of ERROR_FILE_INVALID. Programs should test for files with a length of zero and reject such files.

The size of a file mapping object that is backed by a named file is limited by disk space. The size of a file view is limited to the largest available contiguous block of unreserved virtual memory. This is at most 2 GB minus the virtual memory already reserved by the process.

The size of the file mapping object that you select controls how far into the file you can «see» with memory mapping. If you create a file mapping object that is 500 Kb in size, you have access only to the first 500 Kb of the file, regardless of the size of the file. Since it does not cost you any system resources to create a larger file mapping object, create a file mapping object that is the size of the file (set the dwMaximumSizeHigh and dwMaximumSizeLow parameters of CreateFileMapping both to zero) even if you do not expect to view the entire file. The cost in system resources comes in creating the views and accessing them.

If you want to view a portion of the file that does not start at the beginning of the file, you must create a file mapping object. This object is the size of the portion of the file that you want to view plus the offset into the file.

Читайте также:  Windows zver просит пароль

Framework File Objects

When an application or a driver attempts to access a device, typically by creating or opening a file, the operating system sends a file creation request to the driver stack. When the application or driver has finished using the device, the system sends file cleanup and close requests to the driver stack. The request types of these three requests are WdfRequestTypeCreate, WdfRequestTypeCleanup, and WdfRequestTypeClose, respectively.

Typically, unless your driver has called WdfDeviceInitSetExclusive, the driver must perform file-specific or other access-specific operations when it receives file creation, cleanup, and close requests, because multiple files can be open simultaneously or multiple applications can access the device simultaneously. The driver must therefore keep track of the I/O requests that are associated with each file or application.

The framework defines framework file objects, which represent an application or driver’s means for accessing a device, such as a file, directory, volume, mail slot, named pipe, or the entire device. A file name can be associated with a file object, but the meaning of a file name is driver-specific. For more information about file names, see Controlling Device Namespace Access.

If your driver must handle file operations, it must call WdfDeviceInitSetFileObjectConfig from within its EvtDriverDeviceAdd callback function. The WdfDeviceInitSetFileObjectConfig method receives a WDF_FILEOBJECT_CONFIG structure as input. The driver uses this structure to register its EvtDeviceFileCreate, EvtFileCleanup, and EvtFileClose callback functions and, optionally, to indicate whether the framework should create a framework file object each time that the driver receives a file creation request.

Most drivers that handle file operations store file-specific information in the framework file object’s context space. If your driver handles file operations but does not need to store information in a file object’s context space, the framework does not have to create framework file objects for the driver.

Creating or Opening a File

When the framework receives a file creation request for your function driver, it:

Creates a framework file object that represents the file, unless the driver previously indicated that it does not need to use framework file objects.

Calls your driver’s EvtDeviceFileCreate callback function, if the driver has registered the callback function.

The EvtDeviceFileCreate callback function typically obtains information about the file, such as its name and file object flags. The driver typically stores this information in the context space of the framework file object.

Instead of providing an EvtDeviceFileCreate callback function, the driver can call WdfDeviceConfigureRequestDispatching to set an I/O queue to receive all file creation requests (WdfRequestTypeCreate request type). The driver will subsequently receive file creation requests in the queue’s EvtIoDefault request handler. (An I/O queue cannot receive file creation requests if the DefaultQueue member of the queue’s WDF_IO_QUEUE_CONFIG structure is set to TRUE.)

If your driver does not provide an EvtDeviceFileCreate callback function and does not set up an I/O queue to handle WdfRequestTypeCreate-typed I/O requests, the framework:

Completes all file creation requests for the driver with a status value of STATUS_SUCCESS, if your driver is a function driver.

Forwards all file creation requests to the next-lower driver, if your driver is a filter driver.

(To see how you can change this behavior, see the AutoForwardCleanupClose member of the WDF_FILEOBJECT_CONFIG structure.)

NoteВ В If your function driver does not provide any device interfaces that applications can use to access the driver’s devices, the driver must provide an EvtDeviceFileCreate callback function that completes all file creation requests with a status value for which NT_SUCCESS(status) equals FALSE. Otherwise, a malicious application might attempt to access a device by using the name of the device’s physical device object (PDO). (All PDOs have names.)

If a driver forwards a creation request to an I/O target, the driver must not subsequently complete the request with a failure status value unless the driver receives a failure status value from the I/O target. Otherwise, the lower drivers will not be notified that the creation request failed and might attempt to operate as if the file is open.

If a driver forwards a creation request to an I/O target, the driver cannot set the WDF_REQUEST_SEND_OPTION_SEND_AND_FORGET flag if the framework has created a framework file object for the creation request. Therefore, the driver cannot set the WDF_REQUEST_SEND_OPTION_SEND_AND_FORGET flag for a creation request unless it also sets the WdfFileObjectNotRequired flag as the driver won’t be able to clean up the WDFFILEOBJECT in the event that a driver lower in the stack fails the creation request. Instead, the driver can use any other send-options, for example, send asynchronously with a completion routine or send synchronously. In both cases, the driver must call WdfRequestComplete when it regains control.

Читайте также:  64 разрядная операционная система windows требования

Note that if a driver completes a creation request with an error status, the framework deletes the framework file object but does not call the driver’s EvtFileCleanup or EvtFileClose callback functions. Therefore, if the driver allocates extra object-specific memory outside of the file object’s context space it must provide an EvtCleanupCallback or EvtDestroyCallback callback function that deletes the allocated memory.

For Windows Vista and later, file creation requests can be canceled. Earlier versions of the Windows operating system do not support canceling file creation requests.

The system always creates a Windows Driver Model (WDM) file object for each creation request that comes from a user application. If a driver sends a creation request, it might not create a WDM file object for the request. Typically, the framework does not create a framework file object if a WDM file object is not present. However, if your driver has called WdfDeviceInitSetExclusive and if the driver has set WdfFileObjectWdfCannotUseFsContexts in the FileObjectClass member of the WDF_FILEOBJECT_CONFIG structure, the framework will create a framework file object even if a WDM file object does not exist.

Obtaining File Information

The driver’s EvtDeviceFileCreate callback function can call one or more of the following object methods to obtain information about an application or driver’s access to a device:

WdfFileObjectGetFileName
Returns the file name that is contained in a framework file object.

WdfFileObjectGetFlags
Returns the flags that are contained within a framework file object.

WdfFileObjectWdmGetFileObject
Returns the WDM file object that is associated with a framework file object.

WdfRequestGetParameters
Retrieves the parameters that are associated with a framework request object. If the request type is WdfRequestTypeCreate, the Parameters.Create member of the WDF_REQUEST_PARAMETERS structure contains information about the file creation request.

Typically, the driver stores file information in the framework file object’s context space. When your driver obtains an I/O request from one if its I/O queues, the driver can call WdfRequestGetFileObject to obtain a handle to the framework file object that is associated with the request. The driver can then retrieve the file information that it stored in the framework file object’s context space.

Your driver can search an I/O queue for requests that are associated with a particular file by calling WdfIoQueueRetrieveRequestByFileObject.

If your driver has a pointer to a WDM DEVICE_OBJECT structure, the driver can call WdfDeviceGetFileObject to obtain a handle to the framework file object that is associated with the WDM device object.

Closing a File

When an application or another driver closes a file, the framework receives a cleanup request and a close request for your driver. The framework:

Calls your driver’s EvtFileCleanup and EvtFileClose callback functions, if the driver has registered these callback functions.

Deletes the framework file object that represents the file.

The driver’s EvtFileCleanup and EvtFileClose callback functions receive a handle to the framework file object. The driver can call WdfFileObjectGetDevice to determine which framework device object is associated with the framework file object.

Объект FileSystemObject FileSystemObject object

Предоставляет доступ к файловой системе компьютера. Provides access to a computer’s file system.

Синтаксис Syntax

Scripting.FileSystemObject Scripting.FileSystemObject

Примечания Remarks

Приведенный ниже код иллюстрирует использование объекта FileSystemObject для возврата объекта TextStream, который можно читать, и в который можно записать данные. The following code illustrates how the FileSystemObject object is used to return a TextStream object that can be read from or written to:

В примере кода: In the example code:

  • Функция CreateObject возвращает объект FileSystemObject ( fs ). The CreateObject function returns the FileSystemObject ( fs ).
  • Метод CreateTextFile создает файл в качестве объекта TextStream ( a ). The CreateTextFile method creates the file as a TextStream object ( a ).
  • Метод WriteLine записывает строку текста в созданный текстовый файл. The WriteLine method writes a line of text to the created text file.
  • Метод Close опустошает буфер и закрывает файл. The Close method flushes the buffer and closes the file.

Методы Methods

Метод Method Описание Description
BuildPath BuildPath Добавляет имя в существующий путь. Appends a name to an existing path.
CopyFile CopyFile Копирует один или несколько файлов из одного расположения в другое. Copies one or more files from one location to another.
CopyFolder CopyFolder Копирует одну или несколько папок из одного расположения в другое. Copies one or more folders from one location to another.
CreateFolder CreateFolder Создает новую папку. Creates a new folder.
CreateTextFile CreateTextFile Создает текстовый файл и возвращает объект TextStream, который можно использовать для чтения или записи в файл. Creates a text file and returns a TextStream object that can be used to read from, or write to the file.
DeleteFile DeleteFile Удаляет один или несколько указанных файлов. Deletes one or more specified files.
DeleteFolder DeleteFolder Удаляет одну или несколько указанных папок. Deletes one or more specified folders.
DriveExists DriveExists Проверяет, существует ли указанный диск. Checks if a specified drive exists.
FileExists FileExists Проверяет, существует ли указанный файл. Checks if a specified file exists.
FolderExists FolderExists Проверяет, существует ли указанная папка. Checks if a specified folder exists.
GetAbsolutePathName GetAbsolutePathName Возвращает полный путь из корневого каталога диска для указанного пути. Returns the complete path from the root of the drive for the specified path.
GetBaseName GetBaseName Возвращает базовое имя указанного файла или папки. Returns the base name of a specified file or folder.
GetDrive GetDrive Возвращает объект Drive, соответствующий диску в указанном пути. Returns a Drive object corresponding to the drive in a specified path.
GetDriveName GetDriveName Возвращает имя диска указанного пути. Returns the drive name of a specified path.
GetExtensionName GetExtensionName Возвращает имя расширения файла для последнего компонента в указанном пути. Returns the file extension name for the last component in a specified path.
GetFile GetFile Возвращает объект файла для указанного пути. Returns a File object for a specified path.
GetFileName GetFileName Возвращает имя файла или папки для последнего компонента в указанном пути. Returns the file name or folder name for the last component in a specified path.
GetFolder GetFolder Возвращает объект Folder для указанного пути. Returns a Folder object for a specified path.
GetParentFolderName GetParentFolderName Возвращает имя родительской папки последнего компонента в указанном пути. Returns the name of the parent folder of the last component in a specified path.
GetSpecialFolder GetSpecialFolder Возвращает путь к некоторым специальным папкам Windows. Returns the path to some of Windows’ special folders.
GetTempName GetTempName Возвращает созданный случайным образом временный файл или папку. Returns a randomly generated temporary file or folder.
Move Move Перемещает заданный файл или указанную папку из одного места в другое. Moves a specified file or folder from one location to another.
MoveFile MoveFile Перемещает один или несколько файлов из одного места в другое. Moves one or more files from one location to another.
MoveFolder MoveFolder Перемещает одну или несколько папок из одного места в другое. Moves one or more folders from one location to another.
OpenAsTextStream OpenAsTextStream Открывает указанный файл и возвращает объект TextStream, который можно использовать для считывания, записи и дополнения данных в файле. Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
OpenTextFile OpenTextFile Открывает файл и возвращает объект TextStream, который можно использовать для доступа к файлу. Opens a file and returns a TextStream object that can be used to access the file.
WriteLine WriteLine Записывает заданную строку и символ новой строки в файл TextStream. Writes a specified string and new-line character to a TextStream file.

Свойства Properties

Свойство Property Описание Description
Drives Drives Возвращает коллекцию всех объектов Drive на компьютере. Returns a collection of all Drive objects on the computer.
Name Name Устанавливает или возвращает имя указанного файла или заданной папки. Sets or returns the name of a specified file or folder.
Path Path Возвращает путь для указанного файла, диска или указанной папки. Returns the path for a specified file, folder, or drive.
Size Size Для файлов возвращает размер указанного файла в байтах; для папок возвращает размер всех файлов и вложенных папок в байтах. For files, returns the size, in bytes, of the specified file; for folders, returns the size, in bytes, of all files and subfolders contained in the folder.
Type Type Возвращает сведения о типе файла или папки (например, для файлов с расширением .TXT возвращается «Text Document»). Returns information about the type of a file or folder (for example, for files ending in .TXT, «Text Document» is returned).

См. также See also

Поддержка и обратная связь Support and feedback

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Читайте также:  Создание локального подключения windows 10
Оцените статью