Windows forms сохранить файл

Практическое руководство. Сохранение файлов с помощью компонента SaveFileDialog How to: Save Files Using the SaveFileDialog Component

SaveFileDialogКомпонент позволяет пользователям просматривать файловую систему и выбирать файлы для сохранения. 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.

Сохранение файла с помощью компонента SaveFileDialog 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.

SaveFileDialog OpenFile Чтобы сохранить файл, используйте метод компонента. Use the SaveFileDialog component’s OpenFile method to save the file. Этот метод предоставляет объект, который Stream можно записать в. This method gives you a Stream object you can write to.

В приведенном ниже примере DialogResult свойство используется для получения имени файла, а OpenFile метод — для сохранения файла. The example below uses the DialogResult property to get the name of the file, and the OpenFile method to save the file. OpenFileМетод предоставляет поток для записи файла. The OpenFile method gives you a stream to write the file to.

В приведенном ниже примере имеется Button элемент управления с назначенным ему изображением. In the example below, there is a Button control with an image assigned to it. При нажатии кнопки создается SaveFileDialog экземпляр компонента с фильтром, который разрешает файлы типа. gif,. JPEG и. bmp. 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.

Чтобы получить или задать FileName свойство, сборке требуется уровень привилегий, предоставляемый System.Security.Permissions.FileIOPermission классом. 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. Дополнительные сведения см. в разделе Code Access Security Basics. For more information, see Code Access Security Basics.

В примере предполагается, что в форме есть Button элемент управления со Image свойством, для которого задано значение файла типа. gif,. JPEG или. bmp. The example assumes your form has a Button control with its Image property set to a file of type .gif, .jpeg, or .bmp.

FileDialog FilterIndex Свойство класса (из-за наследования является частью SaveFileDialog класса) использует индекс, отсчитываемый от единицы. 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# и Visual C++) Поместите следующий код в конструктор формы для регистрации обработчика событий. (Visual C# and Visual C++) Place the following code in the form’s constructor to register the event handler.

Читайте также:  Windows 10 winrm enable

Дополнительные сведения о записи файловых потоков см. в статьях BeginWrite и Write . For more information about writing file streams, see BeginWrite and Write.

Некоторые элементы управления, такие как RichTextBox элемент управления, имеют возможность сохранять файлы. Certain controls, such as the RichTextBox control, have the ability to save files.

Save File Dialog Класс

Определение

Запрашивает у пользователя местоположение для сохранения файла. Prompts the user to select a location for saving a file. Этот класс не наследуется. This class cannot be inherited.

Примеры

В следующем примере кода показано создание SaveFileDialog , установка элементов, вызов диалогового окна с помощью ShowDialog метода и сохранение текущего файла. The following code example illustrates creating a SaveFileDialog, setting members, calling the dialog box using the ShowDialog method, and saving the current file. Для примера требуется форма с размещенной на ней кнопкой. The example requires a form with a button placed on it.

Комментарии

Этот класс может либо открыть, либо перезаписать существующий файл, либо создать новый файл. This class can either open and overwrite an existing file or create a new file.

Большая часть функциональных возможностей этого класса находится в FileDialog классе. Most of the functionality for this class is found in the FileDialog class.

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

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

Свойства

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

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

Возвращает или задает значение, указывающее, должен ли этот FileDialog экземпляр автоматически обновлять внешний вид и поведение при работе в Windows Vista. Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista.

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

Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.

(Унаследовано от 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.

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

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

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

Получает или задает GUID, связываемый с этим состоянием диалога. 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. При указании GUID приложение может иметь разные сохраняемые состояния для разных версий диалогового окна в том же приложении (например, диалоговое окно импорта и диалоговое окно открытия). 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).

Эта функция недоступна, если приложение не использует стили оформления или если для AutoUpgradeEnabled задано значение false . This functionality is not available if an application is not using visual styles or if AutoUpgradeEnabled is set to false .

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

Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.

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

Возвращает или задает значение, показывающее, будет ли диалоговое окно запрашивать у пользователя разрешение на создание файла, если указанный файл не существует. Gets or sets a value indicating whether the dialog box prompts the user for permission to create a file if the user specifies a file that does not exist.

Читайте также:  Windows 10 flash tool driver auto installer

Получает коллекцию пользовательских размещений для этого экземпляра FileDialog. Gets the custom places collection for this FileDialog instance.

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

Возвращает или задает расширение имени файла по умолчанию. Gets or sets the default file name extension.

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

Возвращает или задает значение, указывающее, возвращает ли диалоговое окно расположение файла, представленного ярлыком, или возвращает расположение самого ярлыка (.lnk). 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).

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

Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.

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

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.

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

Возвращает или задает строку, содержащую имя файла, выбранного в диалоговом окне. Gets or sets a string containing the file name selected in the file dialog box.

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

Возвращает имена всех выбранных файлов в диалоговом окне. Gets the file names of all selected files in the dialog box.

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

Возвращает или задает текущую строку фильтра имен файлов, которая определяет варианты, доступные в поле диалогового окна «Сохранить как файл типа» или «Файлы типа». 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.

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

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

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

Возвращает или задает начальную папку, отображенную диалоговым окном файла. Gets or sets the initial directory displayed by the file dialog box.

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

Возвращает дескриптор экземпляра обработчика Win32 для приложения. Gets the Win32 instance handle for the application.

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

Получает значения для инициализации класса FileDialog. Gets values to initialize the FileDialog.

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

Возвращает или задает значение, показывающее, будет ли диалоговое окно Save As выводить предупреждение, если файл с указанным именем уже существует. Gets or sets a value indicating whether the Save As dialog box displays a warning if the user specifies a file name that already exists.

Получает или задает значение, указывающее, восстанавливает ли диалоговое окно ранее выбранный каталог в качестве текущего каталога перед закрытием. Gets or sets a value indicating whether the dialog box restores the directory to the previously selected directory before closing.

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

Возвращает или задает значение, определяющее, отображается ли кнопка Справка в диалоговом окне работы с файлами. Gets or sets a value indicating whether the Help button is displayed in the file dialog box.

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

Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.

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

Возвращает или задает значение, определяющее, поддерживает ли диалоговое окно отображение и сохранение файлов, которые содержат несколько расширений имени. Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.

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

Получает или задает объект, содержащий данные элемента управления. Gets or sets an object that contains data about the control.

Читайте также:  Печать пробной страницы mac os

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

Возвращает или задает заголовок диалогового окна файла. Gets or sets the file dialog box title.

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

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

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

Методы

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

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

Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.

(Унаследовано от Component) Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the Component and optionally releases the managed resources.

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

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

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

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

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

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) GetService(Type)

Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.

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

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

(Унаследовано от 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.

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

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

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

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

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

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

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

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

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

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

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

Открывает выбранный пользователем файл с разрешением на чтение и запись. Opens the file with read/write permission selected by the user.

Определяет процедуру окна-владельца, которая переопределяется, чтобы добавить специальные функции для общего диалогового окна. Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.

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

Возвращает всем параметрам диалогового окна значения по умолчанию. Resets all dialog box options to their default values.

Указывает общее диалоговое окно. Specifies a common dialog box.

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

Запускает общее диалоговое окно с заданным по умолчанию владельцем. Runs a common dialog box with a default owner.

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

Запускает общее диалоговое окно с указанным владельцем. Runs a common dialog box with the specified owner.

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

Представляет строковую версию этого объекта. Provides a string version of this object.

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

События

Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.

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

Происходит при нажатии пользователем кнопки Открыть или Сохранить в диалоговом окне файла. Occurs when the user clicks on the Open or Save button on a file dialog box.

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

Происходит при нажатии пользователем кнопки справки в общем диалоговом окне. Occurs when the user clicks the Help button on a common dialog box.

Оцените статью