- Как открыть файлы с помощью OpenFileDialog How to: Open files with the OpenFileDialog
- Пример. чтение файла в виде потока с помощью StreamReader Example: Read a file as a stream with StreamReader
- Пример. Открытие файла из отфильтрованного выделенного фрагмента с помощью OpenFile Example: Open a file from a filtered selection with OpenFile
- Open File Dialog Class
- Definition
- Examples
- Remarks
- Constructors
- Properties
- Methods
- Events
- Html Window. Open Method
- Definition
- Overloads
- Open(String, String, String, Boolean)
- Parameters
- Returns
- Remarks
- Applies to
- Open(Uri, String, String, Boolean)
- Parameters
- Returns
- Examples
- Remarks
Как открыть файлы с помощью OpenFileDialog How to: Open files with the OpenFileDialog
System.Windows.Forms.OpenFileDialogКомпонент открывает диалоговое окно Windows для обзора и выбора файлов. The System.Windows.Forms.OpenFileDialog component opens the Windows dialog box for browsing and selecting files. Чтобы открыть и прочитать выбранные файлы, можно использовать OpenFileDialog.OpenFile метод или создать экземпляр System.IO.StreamReader класса. To open and read the selected files, you can use the OpenFileDialog.OpenFile method, or create an instance of the System.IO.StreamReader class. В следующих примерах показаны оба подхода. The following examples show both approaches.
В .NET Framework для получения или задания FileName свойства требуется уровень привилегий, предоставляемый System.Security.Permissions.FileIOPermission классом. In .NET Framework, to get or set the FileName property requires a privilege level granted by the System.Security.Permissions.FileIOPermission class. В примерах выполняется FileIOPermission Проверка разрешений и может вызываться исключение из-за недостаточных привилегий при выполнении в контексте частичного доверия. The examples run a FileIOPermission permission check, and can throw an exception due to insufficient privileges if run in a partial-trust context. Дополнительные сведения см. в статье основы управления доступом для кода. For more information, see Code access security basics.
Вы можете собрать и запустить эти примеры как .NET Framework приложения из командной строки C# или Visual Basic. You can build and run these examples as .NET Framework apps from the C# or Visual Basic command line. Дополнительные сведения см. в разделе Построение из командной строки с помощью csc.exe или Сборка из командной строки. For more information, see Command-line building with csc.exe or Build from the command line.
Начиная с .NET Core 3,0, можно также создавать и запускать примеры как приложения Windows .NET Core из папки с файлом проекта .NET Core Windows Forms . csproj . Starting with .NET Core 3.0, you can also build and run the examples as Windows .NET Core apps from a folder that has a .NET Core Windows Forms .csproj project file.
Пример. чтение файла в виде потока с помощью StreamReader Example: Read a file as a stream with StreamReader
В следующем примере используется Button обработчик событий Windows Forms элемента управления Click для открытия OpenFileDialog с помощью ShowDialog метода. The following example uses the Windows Forms Button control’s Click event handler to open the OpenFileDialog with the ShowDialog method. После того как пользователь выберет файл и нажмет кнопку ОК, экземпляр StreamReader класса считывает файл и отображает его содержимое в текстовом поле формы. After the user chooses a file and selects OK, an instance of the StreamReader class reads the file and displays its contents in the form’s text box. Дополнительные сведения о чтении из файловых потоков см FileStream.BeginRead . в разделе и FileStream.Read . For more information about reading from file streams, see FileStream.BeginRead and FileStream.Read.
Пример. Открытие файла из отфильтрованного выделенного фрагмента с помощью OpenFile Example: Open a file from a filtered selection with OpenFile
В следующем примере Button обработчик событий элемента управления используется Click для открытия OpenFileDialog с фильтром, который отображает только текстовые файлы. The following example uses the Button control’s Click event handler to open the OpenFileDialog with a filter that shows only text files. После того как пользователь выберет текстовый файл и нажмет кнопку ОК, OpenFile для открытия файла в блокноте используется метод. After the user chooses a text file and selects OK, the OpenFile method is used to open the file in Notepad.
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.
Html Window. Open Method
Definition
Displays a file in the named window.
Overloads
Displays a file in the named window.
Displays a file in the named window.
Open(String, String, String, Boolean)
Displays a file in the named window.
Parameters
The Uniform Resource Locator that describes the location of the file to load.
The name of the window in which to open the resource. This may be a developer-supplied name, or one of the following special values:
_blank : Opens urlString in a new window. Works the same as a call to OpenNew(String, String).
_media : Opens urlString in the Media bar.
_parent : Opens urlString in the window that created the current window.
_search : Opens urlString in the Search bar.
_self : Opens urlString in the current window.
_top : If called against a window belonging to a FRAME element, opens urlString in the window hosting its FRAMESET . Otherwise, acts the same as _self .
A comma-delimited string consisting of zero or more of the following options in the form name=value . Except for the left , top , height , and width options, which take arbitrary integers, each option accepts yes or 1 , and no or 0 , as valid values.
channelmode : Used with the deprecated channels technology of Internet Explorer 4.0. Default is no .
directories : Whether the window should display directory navigation buttons. Default is yes .
height : The height of the window’s client area, in pixels. The minimum is 100; attempts to open a window smaller than this will cause the window to open according to the Internet Explorer defaults.
left : The left (x-coordinate) position of the window, relative to the upper-left corner of the user’s screen, in pixels. Must be a positive integer.
location : Whether to display the Address bar, which enables users to navigate the window to a new URL. Default is yes .
menubar : Whether to display menus on the new window. Default is yes .
resizable : Whether the window can be resized by the user. Default is yes .
scrollbars : Whether the window has horizontal and vertical scroll bars. Default is yes .
status : Whether the window has a status bar at the bottom. Default is yes .
titlebar : Whether the title of the current page is displayed. Setting this option to no has no effect within a managed application; the title bar will always appear.
toolbar : Whether toolbar buttons such as Back, Forward, and Stop are visible. Default is yes .
top : The top (y-coordinate) position of the window, relative to the upper-left corner of the user’s screen, in pixels. Must be a positive integer.
width : The width of the window’s client area, in pixels. The minimum is 100; attempts to open a window smaller than this will cause the window to open according to the Internet Explorer defaults.
Whether urlString replaces the current window’s URL in the navigation history. This will effect the operation of methods on the HtmlHistory class.
Returns
An HtmlWindow representing the new window, or the previously created window named by the target parameter.
Remarks
The target parameter can name a window that was created as the result of a previous call to Open. The parameter may also point to a window opened by clicking on a hyperlink ( A element) or a FORM element that uses the TARGET attribute to open its URL in a new window. The following HTML code will open a new window named orderWindow when the user clicks it:
If you supply any options for the windowOptions parameter, any option not included is automatically disabled. In other words, if you only specify by way of windowOptions that you want a status bar, then the menu bar, toolbar, title, scroll bars, and so on will not be displayed unless you explicitly enable them by way of windowOptions .
If the file referenced by url is an HTML file, text file, or other file type that can be hosted inside of Internet Explorer, it will be displayed in the named window. If the file cannot be displayed inside of Internet Explorer, and the window named by target does not already exist, then the window will open only long enough for Internet Explorer to download the resource; it will close immediately afterwards.
When you create new windows using Open or OpenNew, it causes the HTML Document Object Model to open a new instance of Internet Explorer. If you do not call Close on all of the windows you have created, this instance of Internet Explorer will remain running even after your application has quit.
If you use Open to load a URL in an existing window, windowOptions will be ignored; the window will retain the dimensions, appearance, and screen location first given it by the initial call to Open.
Applies to
Open(Uri, String, String, Boolean)
Displays a file in the named window.
Parameters
The Uniform Resource Locator that describes the location of the file to load.
The name of the window in which to open the resource. This can be a developer-supplied name, or one of the following special values:
_blank : Opens url in a new window. Works the same as a call to OpenNew(String, String).
_media : Opens url in the Media bar.
_parent : Opens url in the window that created the current window.
_search : Opens url in the Search bar.
_self : Opens url in the current window.
_top : If called against a window belonging to a FRAME element, opens url in the window hosting its FRAMESET . Otherwise, acts the same as _self .
A comma-delimited string consisting of zero or more of the following options in the form name=value . Except for the left , top , height , and width options, which take arbitrary integers, each option accepts yes or 1 , and no or 0 , as valid values.
channelmode : Used with the deprecated channels technology of Internet Explorer 4.0. Default is no .
directories : Whether the window should display directory navigation buttons. Default is yes .
height : The height of the window’s client area, in pixels. The minimum is 100; attempts to open a window smaller than this will cause the window to open according to The Internet Explorer defaults.
left : The left (x-coordinate) position of the window, relative to the upper-left corner of the user’s screen, in pixels. Must be a positive integer.
location : Whether to display the Address bar, which enables users to navigate the window to a new URL. Default is yes .
menubar : Whether to display menus on the new window. Default is yes .
resizable : Whether the window can be resized by the user. Default is yes .
scrollbars : Whether the window has horizontal and vertical scroll bars. Default is yes .
status : Whether the window has a status bar at the bottom. Default is yes .
titlebar : Whether the title of the current page is displayed. Setting this option to no has no effect within a managed application; the title bar will always appear.
toolbar : Whether toolbar buttons such as Back, Forward, and Stop are visible. Default is yes .
top : The top (y-coordinate) position of the window, relative to the upper-left corner of the user’s screen, in pixels. Must be a positive integer.
width : The width of the window’s client area, in pixels. The minimum is 100; attempts to open a window smaller than this will cause the window to open according to The Internet Explorer defaults.
Whether url replaces the current window’s URL in the navigation history. This will effect the operation of methods on the HtmlHistory class.
Returns
An HtmlWindow representing the new window, or the previously created window named by the target parameter.
Examples
The following code example contains two methods:
The first opens a URL in a window named displayWindow , which it creates with a status bar displayed.
The second opens another URL in the same window, but specifies that only the location bar should be displayed.
Notice that the dimensions of the window and the controls that are displayed depends on which URL is opened first. The code example requires that your form contains a WebBrowser control named WebBrowser1 .
Remarks
The target parameter can name a window that was created as the result of a previous call to Open. The parameter may also point to a window opened by clicking on a hyperlink ( A element) or a FORM element that uses the TARGET attribute to open its URL in a new window. The following HTML code will open a new window named orderWindow when the user clicks it:
If you supply any options for the windowOptions parameter, any option not included is automatically disabled. In other words, if you only specify by way of windowOptions that you want a status bar, then the menu bar, toolbar, title, scroll bars, and so on will not be displayed unless you explicitly enable them by way of windowOptions .
If the file referenced by url is an HTML file, text file, or other file type that can be hosted inside of Internet Explorer, it will be displayed in the named window. If the file cannot be displayed inside of Internet Explorer, and the window named by target does not already exist, then the window will open only long enough for Internet Explorer to download the resource; it will close immediately afterwards.
When you create new windows using Open or OpenNew, it causes the HTML Document Object Model to open a new instance of Internet Explorer. If you do not call Close on all of the windows you have created, this instance of Internet Explorer will remain running even after your application has quit.
If you use Open to load a URL in an existing window, windowOptions will be ignored; the window will retain the dimensions, appearance, and screen location first given it by the initial call to Open .