OpenFileDialog Класс
Определение
Представляет общее диалоговое окно, позволяющее пользователю задать имя файла для одного или нескольких открываемых файлов.Represents a common dialog box that allows a user to specify a filename for one or more files to open.
public ref class OpenFileDialog sealed : Microsoft::Win32::FileDialog
public sealed class OpenFileDialog : Microsoft.Win32.FileDialog
type OpenFileDialog = class
inherit FileDialog
Public NotInheritable Class OpenFileDialog
Inherits FileDialog
- Наследование
Примеры
В следующем примере показано, как создать объект OpenFileDialog , который содержит имя файла по умолчанию и тип расширения.The following example shows how to create an OpenFileDialog that contains a default file name and extension type.
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
' Configure open file dialog box
Dim dlg As New Microsoft.Win32.OpenFileDialog()
dlg.FileName = "Document" ' Default file name
dlg.DefaultExt = ".txt" ' Default file extension
dlg.Filter = "Text documents (.txt)|*.txt" ' Filter files by extension
' Show open file dialog box
Dim result? As Boolean = dlg.ShowDialog()
' Process open file dialog box results
If result = True Then
' Open document
Dim filename As String = dlg.FileName
End If
Комментарии
На следующем рисунке показан объект OpenFileDialog для Windows VistaWindows Vista.The following figure shows an OpenFileDialog for Windows VistaWindows Vista.
![Диалоговое окно «Открыть»] (~/add/media/dialogboxesoverviewfigure2.png "Диалоговое окно «Открыть»")
Начиная с Windows VistaWindows Vista, диалоговые окна открытия и сохранения файлов имеют панель « Избранные ссылки » в левой части диалогового окна, которая позволяет пользователю быстро перейти в другое расположение.Starting in Windows VistaWindows 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. Чтобы задать этот список ссылок, используйте свойство.CustomPlacesUse the CustomPlaces property to set this list of links.
Использование текста XAMLXAML Text Usage
Этот управляемый класс нельзя объявить XAMLXAMLв.You cannot declare this managed class in XAMLXAML.
Конструкторы
OpenFileDialog() |
Инициализирует новый экземпляр класса OpenFileDialog.Initializes a new instance of the OpenFileDialog class. |
Свойства
AddExtension |
Получает или задает значение, указывающее, добавляет ли диалоговое окно открытия или сохранения файла расширение к имени файла автоматически, если пользователь опустил расширение.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. |
Options |
Получает флаги стандартного диалогового окна открытия или сохранения файлов Win32Win32, используемые этими диалоговыми окнами для инициализации.Gets the Win32Win32 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. |
RestoreDirectory |
Это свойство не реализовано.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. |
Tag |
Получает или задает объект, связанный с диалоговым окном.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 |
Получает или задает значение, указывающее, принимает ли диалоговое окно только допустимые имена файлов Win32Win32.Gets or sets a value indicating whether the dialog accepts only valid Win32Win32 file names. (Унаследовано от FileDialog) |
Методы
CheckPermissionsToShowDialog() |
Определяет, достаточны ли разрешения для отображения диалогового окна.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. |
OpenFiles() |
Создает массив, содержащий один поток только для чтения для каждого файла, выбранного пользователем в диалоговом окне OpenFileDialog.Creates an array that contains one read-only stream for each file selected by the user using OpenFileDialog. |
Reset() |
Восстанавливает для всех свойств OpenFileDialog значения по умолчанию.Resets all OpenFileDialog properties to their default values. |
RunDialog(IntPtr) |
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) |
События
FileOk |
Возникает, когда пользователь выбирает имя файла, нажав кнопку Открыть в диалоговом окне 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. (Унаследовано от FileDialog) |