Save File Dialog Класс
Определение
Представляет общее диалоговое окно, позволяющее пользователю задать имя файла, чтобы сохранить файл под другим именем. Represents a common dialog that allows the user to specify a filename to save a file as. Объект SaveFileDialog не может использоваться приложением, выполняемым с частичным доверием. SaveFileDialog cannot be used by an application that is executing under partial trust.
Примеры
В следующем примере показано, как создать SaveFileDialog и обработать результат. The following example demonstrates how to create a SaveFileDialog and process the result.
Комментарии
На следующем рисунке показана SaveFileDialog система Windows Vista. The following figure shows a SaveFileDialog 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.
Конструкторы
Инициализирует новый экземпляр класса SaveFileDialog. Initializes a new instance of the SaveFileDialog 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)
Получает или задает значение, указывающее, отображает ли диалоговое окно открытия или сохранения файла предупреждение, если пользователь указал несуществующее имя файла. 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)
Получает или задает значение, указывающее, отображается ли предупреждение, если пользователь вводит неверный путь или имя файла. Gets or sets a value that specifies whether warnings are displayed if the user types invalid paths and file names.
(Унаследовано от FileDialog)
Получает или задает значение, показывающее, будет ли диалоговое окно SaveFileDialog запрашивать у пользователя разрешение на создание файла, если указанный пользователем файл не существует. Gets or sets a value indicating whether SaveFileDialog prompts the user for permission to create a file if the user specifies a file that does not exist.
Получает или задает список настраиваемых расположений для диалоговых окон. Gets or sets the list of custom places for file dialog boxes.
(Унаследовано от FileDialog)
Получает или задает строковое значение, которое определяет расширение, используемое по умолчанию для фильтрации списка отображаемых файлов. Gets or sets a value that specifies the default extension string to use to filter the list of files that are displayed.
(Унаследовано от FileDialog)
Получает или задает значение, указывающее, что диалоговое окно возвращает местоположение файла, на который указывает ярлык, или местоположение файла ярлыка (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)
Получает или задает строку, содержащую полный путь к файлу, выбранному в диалоговом окне открытия или сохранения файла. Gets or sets a string containing the full path of the file selected in a file dialog.
(Унаследовано от FileDialog)
Получает массив, содержащий имена всех выбранных файлов. Gets an array that contains one file name for each selected file.
(Унаследовано от FileDialog)
Получает или задает строку фильтра, определяющую, какие типы файлов отображаются в диалоговом окне OpenFileDialog или SaveFileDialog. Gets or sets the filter string that determines what types of files are displayed from either the OpenFileDialog or SaveFileDialog.
(Унаследовано от FileDialog)
Получает или задает индекс фильтра, выбранного в настоящий момент в диалоговом окне открытия или сохранения файла. Gets or sets the index of the filter currently selected in a file dialog.
(Унаследовано от FileDialog)
Получает или задает начальный каталог, отображаемый диалоговым окном открытия или сохранения файла. Gets or sets the initial directory that is displayed by a file dialog.
(Унаследовано от FileDialog)
Возвращает общие Флаги диалогового окна Win32, используемые в диалоговых окнах файлов для инициализации. Gets the Win32 common file dialog flags that are used by file dialogs for initialization.
(Унаследовано от FileDialog)
Получает или задает значение, показывающее, будет ли диалоговое окно SaveFileDialog выводить предупреждение, если файл с указанным именем уже существует. Gets or sets a value indicating whether SaveFileDialog displays a warning if the user specifies the name of a file that already exists.
Это свойство не реализовано. This property is not implemented.
(Унаследовано от FileDialog)
Получает строку, содержащую только имя выбранного файла. Gets a string that only contains the file name for the selected file.
(Унаследовано от FileDialog)
Получает массив, содержащий по одному безопасному имени для каждого выбранного файла. Gets an array that contains one safe file name for each selected file.
(Унаследовано от FileDialog)
Получает или задает объект, связанный с диалоговым окном. Gets or sets an object associated with the dialog. Таким образом, обеспечивает возможность присоединить к диалоговому окну произвольный объект. This provides the ability to attach an arbitrary object to the dialog.
(Унаследовано от CommonDialog)
Получает или задает текст строки заголовка диалогового окна открытия или сохранения файла. Gets or sets the text that appears in the title bar of a file dialog.
(Унаследовано от FileDialog)
Возвращает или задает значение, указывающее, принимает ли диалоговое окно только допустимые имена файлов 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)
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Определяет процедуру обработки стандартного диалогового окна открытия или сохранения файла, переопределенную для добавления в диалоговое окно общих функций. Defines the common file dialog hook procedure that is overridden to add common functionality to a file dialog.
(Унаследовано от FileDialog)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Вызывает событие FileOk. Raises the FileOk event.
(Унаследовано от FileDialog)
Создает файловый поток на чтение и запись для имени файла, выбранного пользователем с помощью диалогового окна SaveFileDialog. Creates a read-write file stream for the filename selected by the user using SaveFileDialog.
Восстанавливает для всех свойств SaveFileDialog значения по умолчанию. Resets all SaveFileDialog 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)
Отображает общее диалоговое окно. Displays a common dialog.
(Унаследовано от CommonDialog)
Отображает общее диалоговое окно. Displays a common dialog.
(Унаследовано от CommonDialog)
Возвращает строку, представляющую диалоговое окно открытия или сохранения файла. 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.
How to: Save Files Using the SaveFileDialog Component
The SaveFileDialog component allows users to browse the file system and select files to be saved. The dialog box returns the path and name of the file the user has selected in the dialog box. However, you must write the code to actually write the files to disk.
To save a file using the SaveFileDialog component
Display the Save File dialog box and call a method to save the file selected by the user.
Use the SaveFileDialog component’s OpenFile method to save the file. This method gives you a Stream object you can write to.
The example below uses the DialogResult property to get the name of the file, and the OpenFile method to save the file. The OpenFile method gives you a stream to write the file to.
In the example below, there is a Button control with an image assigned to it. When you click the button, a SaveFileDialog component is instantiated with a filter that allows files of type .gif, .jpeg, and .bmp. If a file of this type is selected in the Save File dialog box, the button’s image is saved.
To get or set the FileName property, your assembly requires a privilege level granted by the System.Security.Permissions.FileIOPermission class. If you are running in a partial-trust context, the process might throw an exception due to insufficient privileges. For more information, see Code Access Security Basics.
The example assumes your form has a Button control with its Image property set to a file of type .gif, .jpeg, or .bmp.
The FileDialog class’s FilterIndex property (which, due to inheritance, is part of the SaveFileDialog class) uses a one-based index. This is important if you are writing code to save data in a specific format (for example, saving a file in plain text versus binary format). This property is featured in the example below.
(Visual C# and Visual C++) Place the following code in the form’s constructor to register the event handler.
For more information about writing file streams, see BeginWrite and Write.
Certain controls, such as the RichTextBox control, have the ability to save files.
Windows forms c savefiledialog
Уроки 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» будет равен размеру загружаемого изображения, возможно и обратное. Код программы: :
Результат:
Следующий урок >>