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)
Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista.
(Inherited from FileDialog)
Gets a value indicating whether the component can raise an event.
(Inherited from Component)
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)
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)
Gets the IContainer that contains the Component.
(Inherited from Component)
Gets the custom places collection for this FileDialog instance.
(Inherited from FileDialog)
Gets or sets the default file name extension.
(Inherited from FileDialog)
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)
Gets a value that indicates whether the Component is currently in design mode.
(Inherited from Component)
Gets the list of event handlers that are attached to this Component.
(Inherited from Component)
Gets or sets a string containing the file name selected in the file dialog box.
(Inherited from FileDialog)
Gets the file names of all selected files in the dialog box.
(Inherited from FileDialog)
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)
Gets or sets the index of the filter currently selected in the file dialog box.
(Inherited from FileDialog)
Gets or sets the initial directory displayed by the file dialog box.
(Inherited from FileDialog)
Gets the Win32 instance handle for the application.
(Inherited from FileDialog)
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)
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)
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)
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)
Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.
(Inherited from FileDialog)
Gets or sets an object that contains data about the control.
(Inherited from CommonDialog)
Gets or sets the file dialog box title.
(Inherited from FileDialog)
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)
Releases all resources used by the Component.
(Inherited from Component)
Releases the unmanaged resources used by the Component and optionally releases the managed resources.
(Inherited from Component)
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Serves as the default hash function.
(Inherited from Object)
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Returns an object that represents a service provided by the Component or by its Container.
(Inherited from Component)
Gets the Type of the current instance.
(Inherited from Object)
Defines the common dialog box hook procedure that is overridden to add specific functionality to the file dialog box.
(Inherited from FileDialog)
Obtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Creates a shallow copy of the current Object.
(Inherited from Object)
Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Raises the FileOk event.
(Inherited from FileDialog)
Raises the HelpRequest event.
(Inherited from CommonDialog)
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)
Resets all properties to their default values.
Specifies a common dialog box.
(Inherited from FileDialog)
Runs a common dialog box with a default owner.
(Inherited from CommonDialog)
Runs a common dialog box with the specified owner.
(Inherited from CommonDialog)
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)
Occurs when the user clicks on the Open or Save button on a file dialog box.
(Inherited from FileDialog)
Occurs when the user clicks the Help button on a common dialog box.
File Dialog Класс
Определение
Отображает диалоговое окно, с помощью которого пользователь может выбрать файл. Displays a dialog box from which the user can select a file.
Примеры
В следующем примере кода используется OpenFileDialog реализация FileDialog и демонстрируется создание, Настройка свойств и отображение диалогового окна. The following code example uses the OpenFileDialog implementation of FileDialog and illustrates creating, setting of properties, and showing the dialog box. В примере используется ShowDialog метод для отображения диалогового окна и возврата DialogResult . The example uses the ShowDialog method to display the dialog box and return the DialogResult. Для примера требуется форма с Button помещенным в нее и System.IO пространством имен. The example requires a form with a Button placed on it and the System.IO namespace added to it.
Комментарии
FileDialog является абстрактным классом, который содержит общее поведение OpenFileDialog для SaveFileDialog классов и. FileDialog is an abstract class that contains common behavior for the OpenFileDialog and SaveFileDialog classes. Он не предназначен для непосредственного использования, но содержит общее поведение этих двух классов. It is not intended to be used directly but contains common behavior for those two classes. Нельзя создать экземпляр FileDialog . You cannot create an instance of FileDialog. Несмотря на то, что класс объявлен как открытый, его нельзя наследовать, так как он содержит внутренние абстрактные методы. Although the class is declared public, you cannot inherit from it, as it contains internal abstract methods. Чтобы создать диалоговое окно для выбора или сохранения файла, используйте OpenFileDialog или SaveFileDialog . To create a dialog box to select or save a file, use OpenFileDialog or SaveFileDialog.
FileDialog является модальным диалоговым окном; Таким образом, если он показан, он блокирует остальную часть приложения, пока пользователь не выберет файл. FileDialog is a modal dialog box; therefore, when shown, it blocks the rest of the application until the user has chosen a file. При отображении диалогового окна в модальном режиме входные данные (нажатие клавиши или мыши) не могут быть выполнены, за исключением объектов в диалоговом окне. When a dialog box is displayed modally, no input (keyboard or mouse click) can occur except to objects on the dialog box. Программа должна скрыть или закрыть диалоговое окно (обычно в ответ на какое-либо действие пользователя), прежде чем может произойти ввод в вызывающую программу. The program must hide or close the dialog box (usually in response to some user action) before input to the calling program can occur.
При использовании классов, производных от FileDialog , таких как OpenFileDialog и SaveFileDialog , старайтесь не использовать строковые литералы, содержащие абсолютные пути. When you use classes derived from FileDialog, such as OpenFileDialog and SaveFileDialog, avoid using string literals containing absolute paths. Вместо этого следует динамически получать путь с помощью одного или нескольких методов, описанных в следующей таблице. Instead, dynamically obtain the path using one or more of the techniques described in the following table.
Если вы хотите разрешить пользователям выбирать папку вместо файла, используйте FolderBrowserDialog . If you want to enable users to select a folder instead of a file, use the FolderBrowserDialog.
В зависимости от типа приложения, способа хранения данных, связанных с приложением, и причины доступа к файловой системе существует множество способов, с помощью которых можно создать путь к каталогу. Depending upon the type of application, how data associated with the application is stored, and the reason for accessing the file system, there are many possible ways in which you can create a directory path. В следующей таблице показаны методы динамического создания путей. The following table shows the techniques for creating paths dynamically.
Путь или категория программы Path or program category | Класс и элементы для использования Class and members to use |
---|---|
Стандартные пути Windows, такие как Program Files, MyDocuments, Desktop и т. д. Standard Windows paths, such as Program Files, MyDocuments, the Desktop and so on | Этот System.Environment класс является наиболее полным источником для этих элементов, как через статические методы, например SystemDirectory , или через GetFolderPath метод, используя одно из Environment.SpecialFolder перечисляемых значений. The System.Environment class is the most complete source for these, either through its static methods, such as SystemDirectory, or through the GetFolderPath method, using one of the Environment.SpecialFolder enumerated values. |
Пути, связанные с текущим приложением Paths related to the current application | ApplicationКласс имеет статические члены для получения определенных путей, таких как StartupPath , ExecutablePath , LocalUserAppDataPath и CommonAppDataPath . The Application class has static members to obtain certain paths, such as StartupPath, ExecutablePath, LocalUserAppDataPath, and CommonAppDataPath. GetTempPathМетод System.IO.Path возвращает путь к временной папке. The GetTempPath method of the System.IO.Path returns the path of the temporary folder. GetCurrentDirectoryМетод System.IO.Directory класса возвращает текущий выполняемый каталог приложения. The GetCurrentDirectory method of the System.IO.Directory class returns the application’s current executing directory. RootDirectoryСвойство DriveInfo класса представляет корневой каталог указанного диска. The RootDirectory property of the DriveInfo class represents the specified drive’s root directory. |
Пути, сохраненные как параметры приложения Paths stored as application settings | Доступ к соответствующему свойству параметров приложения класса-оболочки, производного от ApplicationSettingsBase . Access the corresponding applications settings property of the wrapper class derived from ApplicationSettingsBase. Дополнительные сведения см. в разделе Параметры приложения для Windows Forms. For more information, see Application Settings for Windows Forms. |
Хранилище реестра Registry storage | Некоторые приложения хранят сведения о каталоге в реестре. Some applications store directory information in the registry. ApplicationКласс содержит CommonAppDataPath LocalUserAppDataPath Свойства и, которые разрешаются в RegistryKey значение. The Application class has the CommonAppDataPath and LocalUserAppDataPath properties that resolve to a RegistryKey value. |
приложения ClickOnce ClickOnce applications | Для приложений ClickOnce используйте Application члены класса, такие как UserAppDataPath , которые будут возвращать указатель на каталог данных ClickOnce. For ClickOnce applications, use Application class members such as UserAppDataPath, which will return a pointer to the ClickOnce data directory. Дополнительные сведения см. в разделе доступ к локальным и удаленным данным в приложениях ClickOnce. For more information, see Accessing Local and Remote Data in ClickOnce Applications. |
Международные приложения International applications | Для международных приложений извлеките часть относительных путей из строкового ресурса в приложении с помощью System.Resources.ResourceReader класса. For international applications, retrieve the relative path portion from a string resource in your application by using the System.Resources.ResourceReader class. Дополнительные сведения о глобализации и локализации см. в разделе Глобализация и локализация. For more information about globalization and localization, see the topic Globalization and Localization. |
Обратите внимание, что полный путь может быть построен с использованием одного или нескольких описанных методов. Notice that a full path may be built up using one or more of the described techniques. Например, GetFolderPath метод может использоваться для получения пути к папке MyDocuments, а затем можно использовать параметр приложения для добавления относительного подкаталога. For example, the GetFolderPath method might be used to obtain the path to the MyDocuments folder, then an application setting may be used to add a relative subdirectory portion.
System.IO.PathКласс содержит статические члены, помогающие манипулировать абсолютными и относительными путями, тогда System.IO.File как System.IO.Directory классы и имеют статические члены, которые фактически управляют файлами и каталогами соответственно. The System.IO.Path class contains static members to assist in manipulating absolute and relative path strings, whereas the System.IO.File and System.IO.Directory classes have static members that actually manipulate files and directories, respectively.
Если пользователь приложения изменяет папку в FileDialog , в текущем рабочем каталоге приложения задается расположение, указанное в FileDialog . If the user of your application changes the folder in the FileDialog, then the current working directory for your application is set to the location specified in the FileDialog. Чтобы избежать этого, присвойте RestoreDirectory свойству значение true . To prevent this, set the RestoreDirectory property to true .
Является владельцем событием FileOk. Owns the FileOk event.
Свойства
Возвращает или задает значение, определяющее, добавляет ли автоматически диалоговое окно расширение к имени файла, если пользователь опускает данное расширение. 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 экземпляр автоматически обновлять внешний вид и поведение при работе в Windows Vista. Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista.
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Возвращает или задает значение, указывающее, отображается ли в диалоговом окне предупреждение, если пользователь указывает несуществующее имя файла. 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.
Получает или задает 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 .
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Получает коллекцию пользовательских размещений для этого экземпляра FileDialog. Gets the custom places collection for this FileDialog instance.
Возвращает или задает расширение имени файла по умолчанию. Gets or sets the default file name extension.
Возвращает или задает значение, указывающее, возвращает ли диалоговое окно расположение файла, представленного ярлыком, или возвращает расположение самого ярлыка (.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).
Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.
(Унаследовано от Component)
Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.
(Унаследовано от Component)
Возвращает или задает строку, содержащую имя файла, выбранного в диалоговом окне. Gets or sets a string containing the file name selected in the file dialog box.
Возвращает имена всех выбранных файлов в диалоговом окне. Gets the file names of all selected files in the dialog box.
Возвращает или задает текущую строку фильтра имен файлов, которая определяет варианты, доступные в поле диалогового окна «Сохранить как файл типа» или «Файлы типа». 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.
Возвращает или задает индекс фильтра, выбранного в настоящий момент в диалоговом окне файла. Gets or sets the index of the filter currently selected in the file dialog box.
Возвращает или задает начальную папку, отображенную диалоговым окном файла. Gets or sets the initial directory displayed by the file dialog box.
Возвращает дескриптор экземпляра обработчика Win32 для приложения. Gets the Win32 instance handle for the application.
Получает значения для инициализации класса FileDialog. Gets values to initialize the FileDialog.
Получает или задает значение, указывающее, восстанавливает ли диалоговое окно ранее выбранный каталог в качестве текущего каталога перед закрытием. Gets or sets a value indicating whether the dialog box restores the directory to the previously selected directory before closing.
Возвращает или задает значение, определяющее, отображается ли кнопка Справка в диалоговом окне работы с файлами. Gets or sets a value indicating whether the Help button is displayed in the file dialog box.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Возвращает или задает значение, определяющее, поддерживает ли диалоговое окно отображение и сохранение файлов, которые содержат несколько расширений имени. Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.
Получает или задает объект, содержащий данные элемента управления. Gets or sets an object that contains data about the control.
(Унаследовано от CommonDialog)
Возвращает или задает заголовок диалогового окна файла. Gets or sets the file dialog box title.
Возвращает или задает значение, указывающее, принимает ли диалоговое окно только допустимые имена файлов Win32. Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.
Методы
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Унаследовано от MarshalByRefObject)
Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.
(Унаследовано от Component)
Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the Component and optionally releases the managed resources.
(Унаследовано от Component)
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.
(Унаследовано от Component)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Определяет процедуру обработки общего диалогового окна, переопределенную, чтобы добавить специальные функции в диалоговое окно файла. Defines the common dialog box hook procedure that is overridden to add specific functionality to the file dialog box.
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.
(Унаследовано от MarshalByRefObject)
Вызывает событие FileOk. Raises the FileOk event.
Вызывает событие HelpRequest. Raises the HelpRequest event.
(Унаследовано от CommonDialog)
Определяет процедуру окна-владельца, которая переопределяется, чтобы добавить специальные функции для общего диалогового окна. Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.
(Унаследовано от CommonDialog)
Восстанавливает заданные по умолчанию значения всех свойств. Resets all properties to their default values.
Указывает общее диалоговое окно. Specifies a common dialog box.
Запускает общее диалоговое окно с заданным по умолчанию владельцем. Runs a common dialog box with a default owner.
(Унаследовано от CommonDialog)
Запускает общее диалоговое окно с указанным владельцем. Runs a common dialog box with the specified owner.
(Унаследовано от CommonDialog)
Представляет строковую версию этого объекта. Provides a string version of this object.
События
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.
(Унаследовано от Component)
Происходит при нажатии пользователем кнопки Открыть или Сохранить в диалоговом окне файла. Occurs when the user clicks on the Open or Save button on a file dialog box.
Происходит при нажатии пользователем кнопки справки в общем диалоговом окне. Occurs when the user clicks the Help button on a common dialog box.