- OpenFile function (winbase.h)
- Syntax
- Parameters
- Return value
- Remarks
- File Mode Перечисление
- Определение
- Примеры
- Комментарии
- File. Open Method
- Definition
- Overloads
- Open(String, FileMode)
- Parameters
- Returns
- Exceptions
- Examples
- Remarks
- Applies to
- Open(String, FileMode, FileAccess)
- Parameters
- Returns
- Exceptions
- Examples
- Remarks
- Applies to
- Open(String, FileMode, FileAccess, FileShare)
- Parameters
- Returns
- Exceptions
- Examples
- Remarks
OpenFile function (winbase.h)
Creates, opens, reopens, or deletes a file.
Syntax
Parameters
The name of the file.
The string must consist of characters from the 8-bit Windows character set. The OpenFile function does not support Unicode file names or opening named pipes.
A pointer to the OFSTRUCT structure that receives information about a file when it is first opened.
The structure can be used in subsequent calls to the OpenFile function to see an open file.
The OFSTRUCT structure contains a path string member with a length that is limited to OFS_MAXPATHNAME characters, which is 128 characters. Because of this, you cannot use the OpenFile function to open a file with a path length that exceeds 128 characters. The CreateFile function does not have this path length limitation.
The action to be taken.
This parameter can be one or more of the following values.
Value | Meaning |
---|---|
OF_CANCEL 0x00000800 | Ignored. To produce a dialog box containing a Cancel button, use OF_PROMPT. |
OF_CREATE 0x00001000 | Creates a new file. If the file exists, it is truncated to zero (0) length. |
OF_DELETE 0x00000200 | Deletes a file. |
OF_EXIST 0x00004000 | Opens a file and then closes it. Use this to test for the existence of a file. |
OF_PARSE 0x00000100 | Fills the OFSTRUCT structure, but does not do anything else. |
OF_PROMPT 0x00002000 | Displays a dialog box if a requested file does not exist. A dialog box informs a user that the system cannot find a file, and it contains Retry and Cancel buttons. The Cancel button directs OpenFile to return a file-not-found error message. |
OF_READ 0x00000000 | Opens a file for reading only. |
OF_READWRITE 0x00000002 | Opens a file with read/write permissions. |
OF_REOPEN 0x00008000 | Opens a file by using information in the reopen buffer. |
OF_SHARE_COMPAT 0x00000000 | For MS-DOS–based file systems, opens a file with compatibility mode, allows any process on a specified computer to open the file any number of times. Other efforts to open a file with other sharing modes fail. This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function. |
OF_SHARE_DENY_NONE 0x00000040 | Opens a file without denying read or write access to other processes. On MS-DOS-based file systems, if the file has been opened in compatibility mode by any other process, the function fails. This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function. |
OF_SHARE_DENY_READ 0x00000030 | Opens a file and denies read access to other processes. On MS-DOS-based file systems, if the file has been opened in compatibility mode, or for read access by any other process, the function fails. This flag is mapped to the FILE_SHARE_WRITE flag of the CreateFile function. |
OF_SHARE_DENY_WRITE 0x00000020 | Opens a file and denies write access to other processes. On MS-DOS-based file systems, if a file has been opened in compatibility mode, or for write access by any other process, the function fails. This flag is mapped to the FILE_SHARE_READ flag of the CreateFile function. |
OF_SHARE_EXCLUSIVE 0x00000010 | Opens a file with exclusive mode, and denies both read/write access to other processes. If a file has been opened in any other mode for read/write access, even by the current process, the function fails. |
OF_VERIFY | Verifies that the date and time of a file are the same as when it was opened previously. This is useful as an extra check for read-only files. |
OF_WRITE 0x00000001 | Opens a file for write access only. |
Return value
If the function succeeds, the return value specifies a file handle to use when performing file I/O. To close the file, call the CloseHandle function using this handle.
If the function fails, the return value is HFILE_ERROR. To get extended error information, call GetLastError.
Remarks
If the lpFileName parameter specifies a file name and extension only, this function searches for a matching file in the following directories and the order shown:
- The directory where an application is loaded.
- The current directory.
- The Windows system directory.
Use the GetSystemDirectory function to get the path of this directory.
The 16-bit Windows system directory.
There is not a function that retrieves the path of this directory, but it is searched.
The Windows directory.
Use the GetWindowsDirectory function to get the path of this directory.
The lpFileName parameter cannot contain wildcard characters.
The OpenFile function does not support the OF_SEARCH flag that the 16-bit Windows OpenFile function supports. The OF_SEARCH flag directs the system to search for a matching file even when a file name includes a full path. Use the SearchPath function to search for a file.
A sharing violation occurs if an attempt is made to open a file or directory for deletion on a remote machine when the value of the uStyle parameter is the OF_DELETE access flag OR’ed with any other access flag, and the remote file or directory has not been opened with FILE_SHARE_DELETE share access. To avoid the sharing violation in this scenario, open the remote file or directory with OF_DELETE access only, or call DeleteFile without first opening the file or directory for deletion.
In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.
Technology | Supported |
---|---|
Server Message Block (SMB) 3.0 protocol | Yes |
SMB 3.0 Transparent Failover (TFO) | Yes |
SMB 3.0 with Scale-out File Shares (SO) | Yes |
Cluster Shared Volume File System (CsvFS) | Yes |
Resilient File System (ReFS) | Yes |
В
CsvFs will do redirected IO for compressed files.
File Mode Перечисление
Определение
Указывает, каким образом операционная система должна открыть файл. Specifies how the operating system should open a file.
Открывает файл, если он существует, и находит конец файла; либо создает новый файл. Opens the file if it exists and seeks to the end of the file, or creates a new file. Для этого требуется разрешение Append. This requires Append permission. FileMode.Append можно использовать только вместе с FileAccess.Write . FileMode.Append can be used only in conjunction with FileAccess.Write . Попытка поиска положения перед концом файла вызывает исключение IOException, и любая попытка чтения заканчивается неудачей, и создает исключение NotSupportedException. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.
Указывает, что операционная система должна создавать новый файл. Specifies that the operating system should create a new file. Если файл уже существует, он будет перезаписан. If the file already exists, it will be overwritten. Для этого требуется разрешение Write. This requires Write permission. Значение FileMode.Create эквивалентно требованию использовать значение CreateNew, если файл не существует, и значение Truncate в противном случае. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. Если файл уже существует, но является скрытым, создается исключение UnauthorizedAccessException. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.
Указывает, что операционная система должна создавать новый файл. Specifies that the operating system should create a new file. Для этого требуется разрешение Write. This requires Write permission. Если файл уже существует, создается исключение IOException. If the file already exists, an IOException exception is thrown.
Указывает, что операционная система должна открыть существующий файл. Specifies that the operating system should open an existing file. Возможность открыть данный файл зависит от значения, задаваемого перечислением FileAccess. The ability to open the file is dependent on the value specified by the FileAccess enumeration. Исключение FileNotFoundException создается, если файл не существует. A FileNotFoundException exception is thrown if the file does not exist.
Указывает, что операционная система должна открыть файл, если он существует, в противном случае должен быть создан новый файл. Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. Если файл открыт с помощью FileAccess.Read , требуется разрешение Read. If the file is opened with FileAccess.Read , Read permission is required. Если доступ к файлу является FileAccess.Write , требуется разрешение Write. If the file access is FileAccess.Write , Write permission is required. Если файл открыт с помощью FileAccess.ReadWrite , требуются разрешения Read и Write. If the file is opened with FileAccess.ReadWrite , both Read and Write permissions are required.
Указывает, что операционная система должна открыть существующий файл. Specifies that the operating system should open an existing file. Если файл открыт, он должен быть усечен таким образом, чтобы его размер стал равен нулю байтов. When the file is opened, it should be truncated so that its size is zero bytes. Для этого требуется разрешение Write. This requires Write permission. Попытки выполнить чтение из файла, открытого с помощью FileMode.Truncate , вызывают исключение ArgumentException. Attempts to read from a file opened with FileMode.Truncate cause an ArgumentException exception.
Примеры
Следующий FileStream конструктор открывает существующий файл ( FileMode.Open ). The following FileStream constructor opens an existing file ( FileMode.Open ).
Комментарии
Пример создания файла и записи текста в файл см. в разделе Практические руководства. запись текста в файл. For an example of creating a file and writing text to a file, see How to: Write Text to a File. Пример считывания текста из файла см. в разделе как читать текст из файла. For an example of reading text from a file, see How to: Read Text from a File. Пример чтения и записи в двоичный файл см. в разделе как читать и записывать в созданный файл данных. For an example of reading from and writing to a binary file, see How to: Read and Write to a Newly Created Data File.
FileMode Параметр задается во многих конструкторах для FileStream , IsolatedStorageFileStream и в Open методах File и FileInfo для управления способом открытия файла. A FileMode parameter is specified in many of the constructors for FileStream, IsolatedStorageFileStream, and in the Open methods of File and FileInfo to control how a file is opened.
FileMode параметры определяют, будет ли файл перезаписан, создан, открыт или какое-либо сочетание. FileMode parameters control whether a file is overwritten, created, opened, or some combination thereof. Используйте Open , чтобы открыть существующий файл. Use Open to open an existing file. Чтобы добавить в файл, используйте Append . To append to a file, use Append . Чтобы усечь файл или создать файл, если он не существует, используйте Create . To truncate a file or create a file if it doesn’t exist, use Create .
File. Open Method
Definition
Opens a FileStream on the specified path.
Overloads
Opens a FileStream on the specified path with read/write access with no sharing.
Opens a FileStream on the specified path, with the specified mode and access with no sharing.
Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.
Open(String, FileMode)
Opens a FileStream on the specified path with read/write access with no sharing.
Parameters
The file to open.
A FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
Returns
A FileStream opened in the specified mode and path, with read/write access and not shared.
Exceptions
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
The specified path, file name, or both exceed the system-defined maximum length.
The specified path is invalid, (for example, it is on an unmapped drive).
An I/O error occurred while opening the file.
path specified a file that is read-only.
This operation is not supported on the current platform.
path specified a directory.
The caller does not have the required permission.
mode is Create and the specified file is a hidden file.
mode specified an invalid value.
The file specified in path was not found.
path is in an invalid format.
Examples
The following code example creates a temporary file and writes some text to it. The example then opens the file, using T:System.IO.FileMode.Open; that is, if the file did not already exist, it would not be created.
Remarks
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
For a list of common I/O tasks, see Common I/O Tasks.
Applies to
Open(String, FileMode, FileAccess)
Opens a FileStream on the specified path, with the specified mode and access with no sharing.
Parameters
The file to open.
A FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
A FileAccess value that specifies the operations that can be performed on the file.
Returns
An unshared FileStream that provides access to the specified file, with the specified mode and access.
Exceptions
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
access specified Read and mode specified Create , CreateNew , Truncate , or Append .
The specified path, file name, or both exceed the system-defined maximum length.
The specified path is invalid, (for example, it is on an unmapped drive).
An I/O error occurred while opening the file.
path specified a file that is read-only and access is not Read .
path specified a directory.
The caller does not have the required permission.
mode is Create and the specified file is a hidden file.
mode or access specified an invalid value.
The file specified in path was not found.
path is in an invalid format.
Examples
The following example opens a file with read-only access.
Remarks
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
Applies to
Open(String, FileMode, FileAccess, FileShare)
Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.
Parameters
The file to open.
A FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
A FileAccess value that specifies the operations that can be performed on the file.
A FileShare value specifying the type of access other threads have to the file.
Returns
A FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.
Exceptions
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
access specified Read and mode specified Create , CreateNew , Truncate , or Append .
The specified path, file name, or both exceed the system-defined maximum length.
The specified path is invalid, (for example, it is on an unmapped drive).
An I/O error occurred while opening the file.
path specified a file that is read-only and access is not Read .
path specified a directory.
The caller does not have the required permission.
mode is Create and the specified file is a hidden file.
mode , access , or share specified an invalid value.
The file specified in path was not found.
path is in an invalid format.
Examples
The following example opens a file with read-only access and with file sharing disallowed.
Remarks
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
For a list of common I/O tasks, see Common I/O Tasks.