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.
Application Класс
Определение
Инкапсулирует приложение Windows Presentation Foundation. Encapsulates a Windows Presentation Foundation application.
Примеры
В следующем примере показано, как стандартное приложение определяется с использованием только разметки: The following example shows how a standard application is defined using only markup:
В следующем примере показано, как стандартное приложение определяется с использованием только кода. The following example shows how a standard application is defined using only code:
В следующем примере показано определение стандартного приложения с помощью сочетания разметки и кода программной части. The following example shows how a standard application is defined using a combination of markup and code-behind.
Комментарии
Application — Это класс, инкапсулирующий функции WPF, относящиеся к приложению, включая следующие: Application is a class that encapsulates WPF application-specific functionality, including the following:
Параметры командной строки и обработка кода выхода: Application.Startup , Application.Exit , Application.Shutdown . Command-Line Parameter and Exit Code Processing: Application.Startup, Application.Exit, Application.Shutdown.
Application реализует Одноэлементный шаблон для предоставления общего доступа к службам окна, свойства и области ресурсов. Application implements the singleton pattern to provide shared access to its window, property, and resource scope services. Следовательно, для каждого экземпляра можно создать только один экземпляр Application класса AppDomain . Consequently, only one instance of the Application class can be created per AppDomain.
Можно реализовать Application с помощью разметки, разметки и кода программной части или кода. You can implement an Application using markup, markup and code-behind, or code. Если Application реализуется с разметкой (разметка или разметка и код программной части), то файл разметки должен быть настроен как элемент Microsoft Build Engine (MSBuild) ApplicationDefinition . If Application is implemented with markup, whether markup or markup and code-behind, the markup file must be configured as an Microsoft build engine (MSBuild) ApplicationDefinition item.
Для автономного приложения не требуется Application объект; можно реализовать пользовательский static метод точки входа ( Main ), который открывает окно без создания экземпляра Application . A standalone application does not require an Application object; it is possible to implement a custom static entry point method ( Main ) that opens a window without creating an instance of Application. Однако для приложений браузера XAML (XBAP) требуется Application объект. However, XAML browser applications (XBAPs) require an Application object.
Конструкторы
Инициализирует новый экземпляр класса Application. Initializes a new instance of the Application class.
Свойства
Возвращает объект Application для текущего AppDomain. Gets the Application object for the current AppDomain.
Возвращает объект Dispatcher, с которым связан этот объект DispatcherObject. Gets the Dispatcher this DispatcherObject is associated with.
(Унаследовано от DispatcherObject)
Получает или задает главное окно приложения. Gets or sets the main window of the application.
Возвращает коллекцию свойств области приложения. Gets a collection of application-scope properties.
Возвращает или задает объект Assembly , предоставляющий универсальные идентификаторы ресурсов (URI) Pack для ресурсов в приложении WPF. Gets or sets the Assembly that provides the pack uniform resource identifiers (URIs) for resources in a WPF application.
Получает или задает коллекцию ресурсов области приложения, например, стилей и кистей. Gets or sets a collection of application-scope resources, such as styles and brushes.
Получает или задает условие, которое является причиной вызова метода Shutdown(). Gets or sets the condition that causes the Shutdown() method to be called.
Получает или задает пользовательский интерфейс, отображающееся автоматически при запуске приложения. Gets or sets a UI that is automatically shown when an application starts.
Возвращает созданные окна приложения. Gets the instantiated windows in an application.
Методы
Определяет, имеет ли вызывающий поток доступ к этому DispatcherObject. Determines whether the calling thread has access to this DispatcherObject.
(Унаследовано от DispatcherObject)
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Выполняет поиск ресурса пользовательского интерфейса (например Style Brush , или) с указанным ключом и создает исключение, если запрошенный ресурс не найден (см. раздел ресурсы XAML). Searches for a user interface (UI) resource, such as a Style or Brush, with the specified key, and throws an exception if the requested resource is not found (see XAML Resources).
Возвращает поток ресурса для файла данных содержания, расположенного в указанном Uri (см. Ресурсы, содержимое и файлы данных WPF-приложения). Returns a resource stream for a content data file that is located at the specified Uri (see WPF Application Resource, Content, and Data Files).
Возвращает файл cookie для расположения, указанного Uri. Retrieves a cookie for the location specified by a Uri.
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Возвращает поток ресурса для исходного файла данных ресурса, расположенного в указанном Uri (см. Ресурсы, содержимое и файлы данных WPF-приложения). Returns a resource stream for a site-of-origin data file that is located at the specified Uri (see WPF Application Resource, Content, and Data Files).
Возвращает поток ресурса для файла данных ресурса, расположенного в указанном Uri (см. Ресурсы, содержимое и файлы данных WPF-приложения). Returns a resource stream for a resource data file that is located at the specified Uri (see WPF Application Resource, Content, and Data Files).
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Загружает XAML-файл, расположенный по указанному универсальному идентификатору ресурса (URI), и преобразует его в экземпляр объекта, указанный в корневом элементе файла XAML. Loads a XAML file that is located at the specified uniform resource identifier (URI) and converts it to an instance of the object that is specified by the root element of the XAML file.
Загружает XAML-файл, расположенный по указанному универсальному идентификатору ресурса (URI), и преобразует его в экземпляр объекта, указанный в корневом элементе файла XAML. Loads a XAML file that is located at the specified uniform resource identifier (URI), and converts it to an instance of the object that is specified by the root element of the XAML file.
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Вызывает событие Activated. Raises the Activated event.
Вызывает событие Deactivated. Raises the Deactivated event.
Вызывает событие Exit. Raises the Exit event.
Вызывает событие LoadCompleted. Raises the LoadCompleted event.
Вызывает событие Navigated. Raises the Navigated event.
Вызывает событие Navigating. Raises the Navigating event.
Вызывает событие NavigationFailed. Raises the NavigationFailed event.
Вызывает событие SessionEnding. Raises the SessionEnding event.
Вызывает событие Startup. Raises the Startup event.
Запускает приложение Windows Presentation Foundation. Starts a Windows Presentation Foundation application.
Запускает приложение Windows Presentation Foundation с открытием указанного окна. Starts a Windows Presentation Foundation application and opens the specified window.
Создает файл cookie для расположения, указанного Uri. Creates a cookie for the location specified by a Uri.
Завершить работу приложения. Shuts down an application.
Завершает работу приложения и передает указанный код завершения операционной системой. Shuts down an application that returns the specified exit code to the operating system.
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.
(Унаследовано от Object)
Осуществляет поиск указанного ресурса. Searches for the specified resource.
Обеспечивает наличие у вызывающего потока доступ к этому DispatcherObject. Enforces that the calling thread has access to this DispatcherObject.
(Унаследовано от DispatcherObject)
События
Происходит, когда приложение становиться активным. Occurs when an application becomes the foreground application.
Происходит, когда приложение перестает быть активным. Occurs when an application stops being the foreground application.
Происходит при генерации приложением исключения, которое не обрабатывается. Occurs when an exception is thrown by an application but not handled.
Происходит непосредственно перед завершением работы приложения и его отменой. Occurs just before an application shuts down and cannot be canceled.
Происходит, когда навигатор в приложении начинает переход к фрагменту содержимого, переход происходит немедленно, если нужный фрагмент находится в текущем содержимом, или после загрузки исходного содержимого XAML, если нужный фрагмент находится в другом содержимом. Occurs when a navigator in the application begins navigation to a content fragment, Navigation occurs immediately if the desired fragment is in the current content, or after the source XAML content has been loaded if the desired fragment is in different content.
Происходит после того, как содержимое, переданное приложению, было загружено, проанализировано и отрисовывается. Occurs when content that was navigated to by a navigator in the application has been loaded, parsed, and has begun rendering.
Происходит, когда содержимое, к которому осуществляется переход, найдено, хотя его загрузка, возможно, еще не завершена. Occurs when the content that is being navigated to by a navigator in the application has been found, although it may not have completed loading.
Происходит при запросе приложением перехода. Occurs when a new navigation is requested by a navigator in the application.
Происходит, когда происходит ошибка при переходе к указанному содержимому. Occurs when an error occurs while a navigator in the application is navigating to the requested content.
Происходит время от времени во время загрузки, управляемой приложением для предоставления информации о статусе загрузки. Occurs periodically during a download that is being managed by a navigator in the application to provide navigation progress information.
Появляется при вызове метода перехода приложения StopLoading , или когда поступил запрос нового перехода во время выполнения текущего. Occurs when the StopLoading method of a navigator in the application is called, or when a new navigation is requested by a navigator while a current navigation is in progress.
Происходит, когда пользователь завершает сеанс Windows, выходя из системы или завершая работу операционной системы. Occurs when the user ends the Windows session by logging off or shutting down the operating system.
Происходит при вызове метода Run() объекта Application. Occurs when the Run() method of the Application object is called.
Явные реализации интерфейса
Запрашивает, доступно ли заданное внешнее свойство в текущей области. Queries for whether a specified ambient property is available in the current scope.
Применяется к
Потокобезопасность
Открытые static ( Shared в Visual Basic) члены этого типа являются потокобезопасными. The public static ( Shared in Visual Basic) members of this type are thread safe. Кроме того, FindResource(Object) методы и TryFindResource(Object) и свойства и Properties Resources являются потокобезопасными. In addition, the FindResource(Object) and TryFindResource(Object) methods and the Properties and Resources properties are thread safe.