- Windows forms open dialog
- Как открыть файлы с помощью 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
- How to: Open files with the OpenFileDialog
- Example: Read a file as a stream with StreamReader
- Example: Open a file from a filtered selection with OpenFile
- Open File Dialog Class
- Definition
- Examples
- Remarks
- Constructors
- Properties
- Methods
- Events
Windows forms open dialog
Уроки Windows Forms C++/C#
openFiledialog и saveFiledialog в MVS C++/C#
В этом уроке будут рассмотрены два очень важных элемента – это «openFiledialog», который будет загружать файл из определённой папки с помощью проводника и «saveFiledialog», который будет сохранять проделанную работу в виде файла в определённую папку, так же с помощью проводника. Все не раз пользовались такой кнопкой, как “Обзор”, загружая фотографии, текстовые документы и прочие файлы. Именно это и будет рассмотрено в этом уроке. В коде этих элементов пишется “фильтр”, в котором указываются форматы файлов, которые нужно загрузить, прочие проводник просто не будет отображать, и так же фильтр ставиться на форматы, в которых файл может быть сохранён. В этом уроке будет рассмотрена работа с изображением — пользователь загружает в «PictureBox» картинку, рисует что-нибудь на ней кистью, как это делать рассмотрено в предыдущем уроке. После того, как картинка видоизменена пользователь сохраняет её в определённую папку, задав ей определённое имя. Создайте проект в приложении «Windows Forms» и перенесите на форму шесть элементов: 1«PictureBox», 3«button», 1«openFiledialog» и 1«saveFileDialog», оформив программу следующим образом:
Button1 будет выполнять функцию загрузки файла. Button2 будет сохранять изменённое изображение. Button3 будет выполнять функцию очистки, если пользователю не понравилось, то как он редактировал изображение. В этом проекте понадобится вызвать три события у “PictureBox” – «MouseMuve», «MouseDown», «MouseUp», поэтому если не знаете как это делать – обязательно посмотрите этот урок. Как всем известно изображения бывают разных форматов, поэтому в фильтре будут написаны все возможные. По мимо этого в коде будет описано свойство, с помощью которого размер «PictureBox» будет равен размеру загружаемого изображения, возможно и обратное. Код программы: :
Результат:
Следующий урок >>
Как открыть файлы с помощью 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.
How to: Open files with the OpenFileDialog
The System.Windows.Forms.OpenFileDialog component opens the Windows dialog box for browsing and selecting files. 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.
In .NET Framework, to get or set the FileName property requires a privilege level granted by the System.Security.Permissions.FileIOPermission class. 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.
You can build and run these examples as .NET Framework apps from the C# or Visual Basic command line. For more information, see Command-line building with csc.exe or Build from the command line.
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.
Example: Read a file as a stream with StreamReader
The following example uses the Windows Forms Button control’s Click event handler to open the OpenFileDialog with the ShowDialog method. 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. For more information about reading from file streams, see FileStream.BeginRead and FileStream.Read.
Example: Open a file from a filtered selection with OpenFile
The following example uses the Button control’s Click event handler to open the OpenFileDialog with a filter that shows only text files. 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.