Windows forms create file dialog

Open File Dialog Class

Definition

Displays a standard dialog box that prompts the user to open a file. This class cannot be inherited.

Examples

The following code example creates an OpenFileDialog, sets several properties to define the file extension filter and dialog behavior, and displays the dialog box using the CommonDialog.ShowDialog method. The example requires a form with a Button placed on it and a reference to the System.IO namespace added to it.

Remarks

This class allows you to check whether a file exists and to open it. The ShowReadOnly property determines whether a read-only check box appears in the dialog box. The ReadOnlyChecked property indicates whether the read-only check box is checked.

Most of the core functionality for this class is found in the FileDialog class.

On a right-to-left operating system, setting the containing form’s RightToLeft property to RightToLeft.Yes localizes the dialog’s File Name, Open, and Cancel buttons. If the property is not set to RightToLeft.Yes, English text is used instead.

If you want to give the user the ability to select a folder instead of a file, use FolderBrowserDialog instead.

Constructors

Initializes an instance of the OpenFileDialog class.

Properties

Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.

(Inherited from FileDialog) AutoUpgradeEnabled

Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista.

(Inherited from FileDialog) CanRaiseEvents

Gets a value indicating whether the component can raise an event.

(Inherited from Component) CheckFileExists

Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.

Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.

(Inherited from FileDialog) ClientGuid

Gets or sets the GUID to associate with this dialog state. Typically, state such as the last visited folder and the position and size of the dialog is persisted based on the name of the executable file. By specifying a GUID, an application can have different persisted states for different versions of the dialog within the same application (for example, an import dialog and an open dialog).

This functionality is not available if an application is not using visual styles or if AutoUpgradeEnabled is set to false .

(Inherited from FileDialog) Container

Gets the IContainer that contains the Component.

(Inherited from Component) CustomPlaces

Gets the custom places collection for this FileDialog instance.

(Inherited from FileDialog) DefaultExt

Gets or sets the default file name extension.

(Inherited from FileDialog) DereferenceLinks

Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk).

(Inherited from FileDialog) DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component) Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component) FileName

Gets or sets a string containing the file name selected in the file dialog box.

(Inherited from FileDialog) FileNames

Gets the file names of all selected files in the dialog box.

(Inherited from FileDialog) Filter

Gets or sets the current file name filter string, which determines the choices that appear in the «Save as file type» or «Files of type» box in the dialog box.

(Inherited from FileDialog) FilterIndex

Gets or sets the index of the filter currently selected in the file dialog box.

(Inherited from FileDialog) InitialDirectory

Gets or sets the initial directory displayed by the file dialog box.

(Inherited from FileDialog) Instance

Gets the Win32 instance handle for the application.

(Inherited from FileDialog) Multiselect

Gets or sets a value indicating whether the dialog box allows multiple files to be selected.

Gets values to initialize the FileDialog.

(Inherited from FileDialog) ReadOnlyChecked

Gets or sets a value indicating whether the read-only check box is selected.

Gets or sets a value indicating whether the dialog box restores the directory to the previously selected directory before closing.

(Inherited from FileDialog) SafeFileName

Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

Gets an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path.

Gets or sets a value indicating whether the Help button is displayed in the file dialog box.

(Inherited from FileDialog) ShowReadOnly

Gets or sets a value indicating whether the dialog box contains a read-only check box.

Gets or sets the ISite of the Component.

(Inherited from Component) SupportMultiDottedExtensions

Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.

(Inherited from FileDialog) Tag

Gets or sets an object that contains data about the control.

(Inherited from CommonDialog) Title

Gets or sets the file dialog box title.

(Inherited from FileDialog) ValidateNames

Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.

(Inherited from FileDialog)

Methods

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject) Dispose()

Releases all resources used by the Component.

Читайте также:  Аудиопоток уже используется windows 10

(Inherited from Component) Dispose(Boolean)

Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object) GetHashCode()

Serves as the default hash function.

(Inherited from Object) GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject) GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component) GetType()

Gets the Type of the current instance.

(Inherited from Object) HookProc(IntPtr, Int32, IntPtr, IntPtr)

Defines the common dialog box hook procedure that is overridden to add specific functionality to the file dialog box.

(Inherited from FileDialog) InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject) MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject) OnFileOk(CancelEventArgs)

Raises the FileOk event.

(Inherited from FileDialog) OnHelpRequest(EventArgs)

Raises the HelpRequest event.

(Inherited from CommonDialog) OpenFile()

Opens the file selected by the user, with read-only permission. The file is specified by the FileName property.

Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.

(Inherited from CommonDialog) Reset()

Resets all properties to their default values.

Specifies a common dialog box.

(Inherited from FileDialog) ShowDialog()

Runs a common dialog box with a default owner.

(Inherited from CommonDialog) ShowDialog(IWin32Window)

Runs a common dialog box with the specified owner.

(Inherited from CommonDialog) ToString()

Provides a string version of this object.

(Inherited from FileDialog)

Events

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component) FileOk

Occurs when the user clicks on the Open or Save button on a file dialog box.

(Inherited from FileDialog) HelpRequest

Occurs when the user clicks the Help button on a common dialog box.

File Dialog. Default Ext Свойство

Определение

Возвращает или задает расширение имени файла по умолчанию. Gets or sets the default file name extension.

Значение свойства

Расширение имени файла по умолчанию. The default file name extension. Возвращенная строка не содержит точка. The returned string does not include the period. Значение по умолчанию — пустая строка. The default value is an empty string («»).

Примеры

В следующем примере кода показано использование RichTextBox.SaveFile методов и RichTextBox.LoadFile с потоками. The following code example demonstrates using the RichTextBox.SaveFile and RichTextBox.LoadFile methods with streams. Он также демонстрирует использование FileName элементов, DefaultExt , SaveFileDialog.CreatePrompt и SaveFileDialog.OverwritePrompt . It also demonstrates using the FileName, DefaultExt, SaveFileDialog.CreatePrompt, and SaveFileDialog.OverwritePrompt members.

Это полный пример, готовый к запуску при копировании в проект. This is a complete example that is ready to run when you copy it to your project.

Комментарии

Когда пользователь приложения указывает имя файла без расширения, FileDialog добавляет расширение к имени файла. When the user of your application specifies a file name without an extension, the FileDialog appends an extension to the file name. Используемое расширение определяется Filter DefaultExt свойствами и. The extension that is used is determined by the Filter and DefaultExt properties. Если фильтр выбран в FileDialog и фильтр указывает расширение, то используется это расширение. If a filter is selected in the FileDialog and the filter specifies an extension, then that extension is used. Если выбранный фильтр использует подстановочный знак вместо расширения, то используется расширение, указанное в DefaultExt свойстве. If the filter selected uses a wildcard in place of the extension, then the extension specified in the DefaultExt property is used.

File Dialog. File Ok Событие

Определение

Происходит при нажатии пользователем кнопки Открыть или Сохранить в диалоговом окне файла. Occurs when the user clicks on the Open or Save button on a file dialog box.

Тип события

Примеры

В следующем примере кода показано использование FileNames свойства, обработка FileOk события и использование Application.DoEvents метода. The following code example demonstrates using the FileNames property, handling the FileOk event and using the Application.DoEvents method. При выполнении примера пользователь может выбрать графические файлы из OpenFileDialog объекта. When the example runs, a user can select graphics files from an OpenFileDialog object. Выбранные файлы отображаются в форме. The selected files are displayed in the form. Application.DoEventsМетод принудительно выполняет перерисовку формы для каждого открытого графического файла. The Application.DoEvents method forces a repaint of the form for each graphics file opened. Чтобы выполнить этот пример, вставьте следующий код в форму, содержащую именованный объект с именем PictureBox PictureBox1 и именем OpenFileDialog OpenFileDialog1 Button fileButton . To run this example paste the following code in a form containing a PictureBox named PictureBox1 , an OpenFileDialog named OpenFileDialog1 , and a Button named fileButton . Вызовите InitializePictureBox InitializeOpenFileDialog методы и из конструктора или Load метода формы. Call the InitializePictureBox and InitializeOpenFileDialog methods from the form’s constructor or Load method. При выполнении примера откройте диалоговое окно, нажав кнопку. When the example is running, display the dialog box by clicking the button.

Комментарии

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For information about handling events, see Handling and Raising Events.

Open File Dialog Класс

Определение

Отображает диалоговое окно, позволяющее пользователю открыть файл. Displays a standard dialog box that prompts the user to open a file. Этот класс не наследуется. This class cannot be inherited.

Примеры

В следующем примере кода создается OpenFileDialog , задается несколько свойств, определяющих фильтр расширения файла и поведение диалогового окна, и отображается диалоговое окно с помощью CommonDialog.ShowDialog метода. The following code example creates an OpenFileDialog, sets several properties to define the file extension filter and dialog behavior, and displays the dialog box using the CommonDialog.ShowDialog method. Для примера требуется форма с Button помещенным на нее, а также ссылка на System.IO пространство имен, добавленное в нее. The example requires a form with a Button placed on it and a reference to the System.IO namespace added to it.

Читайте также:  Windows 98se системные требования

Комментарии

Этот класс позволяет проверить, существует ли файл, и открыть его. This class allows you to check whether a file exists and to open it. ShowReadOnlyСвойство определяет, отображается ли флажок только для чтения в диалоговом окне. The ShowReadOnly property determines whether a read-only check box appears in the dialog box. ReadOnlyCheckedСвойство указывает, установлен ли флажок только для чтения. The ReadOnlyChecked property indicates whether the read-only check box is checked.

Большая часть основных функций для этого класса находится в FileDialog классе. Most of the core functionality for this class is found in the FileDialog class.

В операционной системе с письмом справа налево установка свойства содержащей формы RightToLeft позволяет RightToLeft.Yes локализовать кнопки имя файла, Открыть и отменить диалоговые окна. On a right-to-left operating system, setting the containing form’s RightToLeft property to RightToLeft.Yes localizes the dialog’s File Name, Open, and Cancel buttons. Если свойство не имеет значение RightToLeft.Yes , вместо него используется текст на английском языке. If the property is not set to RightToLeft.Yes, English text is used instead.

Если вы хотите предоставить пользователю возможность выбрать папку вместо файла, используйте FolderBrowserDialog вместо нее. If you want to give the user the ability to select a folder instead of a file, use FolderBrowserDialog instead.

Конструкторы

Инициализирует экземпляр класса OpenFileDialog. Initializes an instance of the OpenFileDialog class.

Свойства

Возвращает или задает значение, определяющее, добавляет ли автоматически диалоговое окно расширение к имени файла, если пользователь опускает данное расширение. Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.

(Унаследовано от FileDialog) AutoUpgradeEnabled

Возвращает или задает значение, указывающее, должен ли этот FileDialog экземпляр автоматически обновлять внешний вид и поведение при работе в Windows Vista. Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista.

(Унаследовано от FileDialog) CanRaiseEvents

Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.

(Унаследовано от Component) CheckFileExists

Возвращает или задает значение, указывающее, отображается ли в диалоговом окне предупреждение, если пользователь указывает несуществующее имя файла. Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.

Возвращает или задает значение, указывающее, отображает ли диалоговое окно предупреждение, если пользователь указывает несуществующий путь. Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.

(Унаследовано от FileDialog) ClientGuid

Получает или задает GUID, связываемый с этим состоянием диалога. Gets or sets the GUID to associate with this dialog state. Как правило, состояние, такое как последняя посещенная папка, а также расположение и размер диалогового окна, сохраняется с учетом имени исполняемого файла. Typically, state such as the last visited folder and the position and size of the dialog is persisted based on the name of the executable file. При указании GUID приложение может иметь разные сохраняемые состояния для разных версий диалогового окна в том же приложении (например, диалоговое окно импорта и диалоговое окно открытия). By specifying a GUID, an application can have different persisted states for different versions of the dialog within the same application (for example, an import dialog and an open dialog).

Эта функция недоступна, если приложение не использует стили оформления или если для AutoUpgradeEnabled задано значение false . This functionality is not available if an application is not using visual styles or if AutoUpgradeEnabled is set to false .

(Унаследовано от FileDialog) Container

Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.

(Унаследовано от Component) CustomPlaces

Получает коллекцию пользовательских размещений для этого экземпляра FileDialog. Gets the custom places collection for this FileDialog instance.

(Унаследовано от FileDialog) DefaultExt

Возвращает или задает расширение имени файла по умолчанию. Gets or sets the default file name extension.

(Унаследовано от FileDialog) DereferenceLinks

Возвращает или задает значение, указывающее, возвращает ли диалоговое окно расположение файла, представленного ярлыком, или возвращает расположение самого ярлыка (.lnk). Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk).

(Унаследовано от FileDialog) DesignMode

Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.

(Унаследовано от Component) Events

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.

(Унаследовано от Component) FileName

Возвращает или задает строку, содержащую имя файла, выбранного в диалоговом окне. Gets or sets a string containing the file name selected in the file dialog box.

(Унаследовано от FileDialog) FileNames

Возвращает имена всех выбранных файлов в диалоговом окне. Gets the file names of all selected files in the dialog box.

(Унаследовано от FileDialog) Filter

Возвращает или задает текущую строку фильтра имен файлов, которая определяет варианты, доступные в поле диалогового окна «Сохранить как файл типа» или «Файлы типа». Gets or sets the current file name filter string, which determines the choices that appear in the «Save as file type» or «Files of type» box in the dialog box.

(Унаследовано от FileDialog) FilterIndex

Возвращает или задает индекс фильтра, выбранного в настоящий момент в диалоговом окне файла. Gets or sets the index of the filter currently selected in the file dialog box.

(Унаследовано от FileDialog) InitialDirectory

Возвращает или задает начальную папку, отображенную диалоговым окном файла. Gets or sets the initial directory displayed by the file dialog box.

Читайте также:  P43 chipset драйвер windows 10

(Унаследовано от FileDialog) Instance

Возвращает дескриптор экземпляра обработчика Win32 для приложения. Gets the Win32 instance handle for the application.

(Унаследовано от FileDialog) Multiselect

Получает или задает значение, указывающее, можно ли в диалоговом окне выбирать несколько файлов. Gets or sets a value indicating whether the dialog box allows multiple files to be selected.

Получает значения для инициализации класса FileDialog. Gets values to initialize the FileDialog.

(Унаследовано от FileDialog) ReadOnlyChecked

Получает или задает значение, указывающее, установлен ли флажок доступности только для чтения. Gets or sets a value indicating whether the read-only check box is selected.

Получает или задает значение, указывающее, восстанавливает ли диалоговое окно ранее выбранный каталог в качестве текущего каталога перед закрытием. Gets or sets a value indicating whether the dialog box restores the directory to the previously selected directory before closing.

(Унаследовано от FileDialog) SafeFileName

Возвращает имя и расширение файла, выбранного в диалоговом окне. Gets the file name and extension for the file selected in the dialog box. Имя файла не включает сведения о пути. The file name does not include the path.

Возвращает массив имен и расширений файлов для всех выбранных в диалоговом окне файлов. Gets an array of file names and extensions for all the selected files in the dialog box. Имена файлов не включают сведений о пути. The file names do not include the path.

Возвращает или задает значение, определяющее, отображается ли кнопка Справка в диалоговом окне работы с файлами. Gets or sets a value indicating whether the Help button is displayed in the file dialog box.

(Унаследовано от FileDialog) ShowReadOnly

Получает или задает значение, указывающее, имеется ли в диалоговом окне флажок «доступно только для чтения». Gets or sets a value indicating whether the dialog box contains a read-only check box.

Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.

(Унаследовано от Component) SupportMultiDottedExtensions

Возвращает или задает значение, определяющее, поддерживает ли диалоговое окно отображение и сохранение файлов, которые содержат несколько расширений имени. Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.

(Унаследовано от FileDialog) Tag

Получает или задает объект, содержащий данные элемента управления. Gets or sets an object that contains data about the control.

(Унаследовано от CommonDialog) Title

Возвращает или задает заголовок диалогового окна файла. Gets or sets the file dialog box title.

(Унаследовано от FileDialog) ValidateNames

Возвращает или задает значение, указывающее, принимает ли диалоговое окно только допустимые имена файлов Win32. Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.

(Унаследовано от FileDialog)

Методы

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Унаследовано от MarshalByRefObject) Dispose()

Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.

(Унаследовано от Component) Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Унаследовано от Component) Equals(Object)

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetHashCode()

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetLifetimeService()

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) GetService(Type)

Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.

(Унаследовано от Component) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) HookProc(IntPtr, Int32, IntPtr, IntPtr)

Определяет процедуру обработки общего диалогового окна, переопределенную, чтобы добавить специальные функции в диалоговое окно файла. Defines the common dialog box hook procedure that is overridden to add specific functionality to the file dialog box.

(Унаследовано от FileDialog) InitializeLifetimeService()

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.

(Унаследовано от MarshalByRefObject) OnFileOk(CancelEventArgs)

Вызывает событие FileOk. Raises the FileOk event.

(Унаследовано от FileDialog) OnHelpRequest(EventArgs)

Вызывает событие HelpRequest. Raises the HelpRequest event.

(Унаследовано от CommonDialog) OpenFile()

Открывает выбранный пользователем файл в режиме «только чтение». Opens the file selected by the user, with read-only permission. Файл задается свойством FileName. The file is specified by the FileName property.

Определяет процедуру окна-владельца, которая переопределяется, чтобы добавить специальные функции для общего диалогового окна. Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.

(Унаследовано от CommonDialog) Reset()

Восстанавливает заданные по умолчанию значения всех свойств. Resets all properties to their default values.

Указывает общее диалоговое окно. Specifies a common dialog box.

(Унаследовано от FileDialog) ShowDialog()

Запускает общее диалоговое окно с заданным по умолчанию владельцем. Runs a common dialog box with a default owner.

(Унаследовано от CommonDialog) ShowDialog(IWin32Window)

Запускает общее диалоговое окно с указанным владельцем. Runs a common dialog box with the specified owner.

(Унаследовано от CommonDialog) ToString()

Представляет строковую версию этого объекта. Provides a string version of this object.

(Унаследовано от FileDialog)

События

Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.

(Унаследовано от Component) FileOk

Происходит при нажатии пользователем кнопки Открыть или Сохранить в диалоговом окне файла. Occurs when the user clicks on the Open or Save button on a file dialog box.

(Унаследовано от FileDialog) HelpRequest

Происходит при нажатии пользователем кнопки справки в общем диалоговом окне. Occurs when the user clicks the Help button on a common dialog box.

Оцените статью