Openfiledialog windows form c

Open File Dialog Класс

Определение

Представляет общее диалоговое окно, позволяющее пользователю задать имя файла для одного или нескольких открываемых файлов. Represents a common dialog box that allows a user to specify a filename for one or more files to open.

Примеры

В следующем примере показано, как создать объект OpenFileDialog , который содержит имя файла по умолчанию и тип расширения. The following example shows how to create an OpenFileDialog that contains a default file name and extension type.

Комментарии

На следующем рисунке показана OpenFileDialog для Windows Vista. The following figure shows an OpenFileDialog for Windows Vista.

Начиная с Windows Vista, диалоговые окна открытия и сохранения файлов имеют панель « Избранные ссылки » в левой части диалогового окна, которая позволяет пользователю быстро перейти в другое расположение. Starting in Windows Vista, open and save file dialog boxes have a Favorite Links panel on the left side of the dialog box that allows the user to quickly navigate to a different location. Эти ссылки называются пользовательскими местами. These links are called custom places. CustomPlacesЧтобы задать этот список ссылок, используйте свойство. Use the CustomPlaces property to set this list of links.

Использование текста XAML XAML Text Usage

Этот управляемый класс нельзя объявить в XAML. You cannot declare this managed class in XAML.

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

Инициализирует новый экземпляр класса OpenFileDialog. Initializes a new instance of the OpenFileDialog class.

Свойства

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

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

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

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

Получает или задает значение, указывающее, отображается ли предупреждение, если пользователь вводит неверный путь или имя файла. Gets or sets a value that specifies whether warnings are displayed if the user types invalid paths and file names.

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

Получает или задает список настраиваемых расположений для диалоговых окон. Gets or sets the list of custom places for file dialog boxes.

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

Получает или задает строковое значение, которое определяет расширение, используемое по умолчанию для фильтрации списка отображаемых файлов. Gets or sets a value that specifies the default extension string to use to filter the list of files that are displayed.

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

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

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

Получает или задает строку, содержащую полный путь к файлу, выбранному в диалоговом окне открытия или сохранения файла. Gets or sets a string containing the full path of the file selected in a file dialog.

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

Получает массив, содержащий имена всех выбранных файлов. Gets an array that contains one file name for each selected file.

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

Получает или задает строку фильтра, определяющую, какие типы файлов отображаются в диалоговом окне OpenFileDialog или SaveFileDialog. Gets or sets the filter string that determines what types of files are displayed from either the OpenFileDialog or SaveFileDialog.

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

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

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

Получает или задает начальный каталог, отображаемый диалоговым окном открытия или сохранения файла. Gets or sets the initial directory that is displayed by a file dialog.

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

Получает или задает параметр, показывающий, позволяет ли диалоговое окно OpenFileDialog пользователям выбирать несколько файлов. Gets or sets an option indicating whether OpenFileDialog allows users to select multiple files.

Читайте также:  Wsl для windows home

Возвращает общие Флаги диалогового окна Win32, используемые в диалоговых окнах файлов для инициализации. Gets the Win32 common file dialog flags that are used by file dialogs for initialization.

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

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

Это свойство не реализовано. This property is not implemented.

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

Получает строку, содержащую только имя выбранного файла. Gets a string that only contains the file name for the selected file.

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

Получает массив, содержащий по одному безопасному имени для каждого выбранного файла. Gets an array that contains one safe file name for each selected file.

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

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

Получает или задает объект, связанный с диалоговым окном. Gets or sets an object associated with the dialog. Таким образом, обеспечивает возможность присоединить к диалоговому окну произвольный объект. This provides the ability to attach an arbitrary object to the dialog.

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

Получает или задает текст строки заголовка диалогового окна открытия или сохранения файла. Gets or sets the text that appears in the title bar of a file dialog.

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

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

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

Методы

Определяет, достаточны ли разрешения для отображения диалогового окна. Determines whether sufficient permissions for displaying a dialog exist.

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

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

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

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

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

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

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

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

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

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

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

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

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

Открывает поток только на чтение для файла, выбранного пользователем с помощью диалогового окна OpenFileDialog. Opens a read-only stream for the file that is selected by the user using OpenFileDialog.

Создает массив, содержащий один поток только для чтения для каждого файла, выбранного пользователем в диалоговом окне OpenFileDialog. Creates an array that contains one read-only stream for each file selected by the user using OpenFileDialog.

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

RunDialog(IntPtr) вызывается для отображения диалогового окна открытия или сохранения файла в производном классе, таком как OpenFileDialog или SaveFileDialog. RunDialog(IntPtr) is called to display a file dialog in a derived class, such as OpenFileDialog and SaveFileDialog.

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

Отображает общее диалоговое окно. Displays a common dialog.

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

Отображает общее диалоговое окно. Displays a common dialog.

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

Возвращает строку, представляющую диалоговое окно открытия или сохранения файла. Returns a string that represents a file dialog.

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

События

Возникает, когда пользователь выбирает имя файла, нажав кнопку Открыть в диалоговом окне OpenFileDialog или кнопку Сохранить в диалоговом окне SaveFileDialog. Occurs when the user selects a file name by either clicking the Open button of the OpenFileDialog or the Save button of the SaveFileDialog.

File Dialog Class

Definition

Displays a dialog box from which the user can select a file.

Examples

The following code example uses the OpenFileDialog implementation of FileDialog and illustrates creating, setting of properties, and showing the dialog box. The example uses the ShowDialog method to display the dialog box and return the DialogResult. The example requires a form with a Button placed on it and the System.IO namespace added to it.

Читайте также:  Windows paint как рисовать

Remarks

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. You cannot create an instance of FileDialog. Although the class is declared public, you cannot inherit from it, as it contains internal abstract methods. To create a dialog box to select or save a file, use OpenFileDialog or SaveFileDialog.

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.

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.

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
Standard Windows paths, such as Program Files, MyDocuments, the Desktop and so on 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 The Application class has static members to obtain certain paths, such as StartupPath, ExecutablePath, LocalUserAppDataPath, and CommonAppDataPath.

The GetTempPath method of the System.IO.Path returns the path of the temporary folder.

The GetCurrentDirectory method of the System.IO.Directory class returns the application’s current executing directory.

The RootDirectory property of the DriveInfo class represents the specified drive’s root directory.

Paths stored as application settings Access the corresponding applications settings property of the wrapper class derived from ApplicationSettingsBase. For more information, see Application Settings for Windows Forms.
Registry storage Some applications store directory information in the registry. The Application class has the CommonAppDataPath and LocalUserAppDataPath properties that resolve to a RegistryKey value.
ClickOnce applications For ClickOnce applications, use Application class members such as UserAppDataPath, which will return a pointer to the ClickOnce data directory. For more information, see Accessing Local and Remote Data in ClickOnce Applications.
International applications 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. 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.

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.

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. To prevent this, set the RestoreDirectory property to true .

Fields

Owns the FileOk event.

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.

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.

(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.

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 .

Gets the IContainer that contains the Component.

(Inherited from Component) CustomPlaces

Gets the custom places collection for this FileDialog instance.

Gets or sets the default file name extension.

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).

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.

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.

Gets the Win32 instance handle for the application.

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.

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.

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

(Inherited from CommonDialog) Title

Gets or sets the file dialog box title.

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

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.

(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.

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.

Raises the HelpRequest event.

(Inherited from CommonDialog) OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr)

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.

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.

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.

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

Читайте также:  Какую консоль для linux
Оцените статью