Последнее обновление: 31.10.2015
Окна открытия и сохранения файла представлены классами OpenFileDialog и SaveFileDialog.
Они имеют во многом схожую функциональность, поэтому рассмотрим их вместе.
OpenFileDialog и SaveFileDialog имеют ряд общих свойств, среди которых можно выделить следующие:
-
DefaultExt
: устанавливает расширение файла, которое добавляется по умолчанию, если пользователь ввел имя файла без расширения -
AddExtension
: при значенииtrue
добавляет к имени файла расширение при его отсуствии. Расширение берется из
свойстваDefaultExt
илиFilter
-
CheckFileExists
: если имеет значениеtrue
, то проверяет существование файла с указанным именем -
CheckPathExists
: если имеет значениеtrue
, то проверяет существование пути к файлу с указанным именем -
FileName
: возвращает полное имя файла, выбранного в диалоговом окне -
Filter
: задает фильтр файлов, благодаря чему в диалоговом окне можно отфильтровать файлы по расширению. Фильтр задается в следующем формате
Название_файлов|*.расширение. Например,Текстовые файлы(*.txt)|*.txt
. Можно задать сразу несколько фильтров, для этого они разделяются
вертикальной линией |. Например,Bitmap files (*.bmp)|*.bmp|Image files (*.jpg)|*.jpg
-
InitialDirectory
: устанавливает каталог, который отображается при первом вызове окна -
Title
: заголовок диалогового окна
Отдельно у класса SaveFileDialog можно еще выделить пару свойств:
-
CreatePrompt
: при значенииtrue
в случае, если указан не существующий файл, то будет отображаться сообщение о его создании -
OverwritePrompt
: при значенииtrue
в случае, если указан существующий файл, то будет отображаться сообщение о том, что файл будет перезаписан
Чтобы отобразить диалоговое окно, надо вызвать метод ShowDialog()
.
Рассмотрим оба диалоговых окна на примере. Добавим на форму текстовое поле textBox1 и две кнопки button1 и button2. Также перетащим с панели инструментов
компоненты OpenFileDialog и SaveFileDialog. После добавления они отобразятся внизу дизайнера формы. В итоге форма будет выглядеть примерно так:
Теперь изменим код формы:
public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += button1_Click; button2.Click += button2_Click; openFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*"; saveFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*"; } // сохранение файла void button2_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.Cancel) return; // получаем выбранный файл string filename = saveFileDialog1.FileName; // сохраняем текст в файл System.IO.File.WriteAllText(filename, textBox1.Text); MessageBox.Show("Файл сохранен"); } // открытие файла void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.Cancel) return; // получаем выбранный файл string filename = openFileDialog1.FileName; // читаем файл в строку string fileText = System.IO.File.ReadAllText(filename); textBox1.Text = fileText; MessageBox.Show("Файл открыт"); } }
По нажатию на первую кнопку будет открываться окно открытия файла. После выбора файла он будет считываться, а его текст будет отображаться в
текстовом поле. Клик на вторую кнопку отобразит окно для сохранения файла, в котором надо установить его название. И после этого произойдет сохранение
текста из текстового поля в файл.
A SaveFileDialog control is used to save a file using Windows SaveFileDialog. A typical SaveFileDialog looks like Figure 1 where you can see the Windows Explorer type features to navigate through folders and save a file in a folder.
Figure 1
Creating a SaveFileDialog
We can create a SaveFileDialog control using a Forms designer at design-time or using the SaveFileDialog class in code at run-time (also known as dynamically). Unlike other Windows Forms controls, a SaveFileDialog does not have and not need visual properties like others.
Note
Even though you can create a SaveFileDialog at design-time it is easier to create a SaveFileDialog at run-time.
Design-time
To create a SaveFileDialog control at design-time, you simply drag and drop a SaveFileDialog control from Toolbox to a Form in Visual Studio. After you drag and drop a SaveFileDialog on a Form, the SaveFileDialog looks like Figure 2.
Figure 2
Adding a SaveFileDialog to a Form adds the following two lines of code.
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
Run-time
Creating a SaveFileDialog control at run-time is merely a work of creating an instance of SaveFileDialog class, setting its properties and adding SaveFileDialog class to the Form controls.
The first step to create a dynamic SaveFileDialog is to create an instance of SaveFileDialog class. The following code snippet creates a SaveFileDialog control object.
SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
ShowDialog method displays the SaveFileDialog.
SaveFileDialog1.ShowDialog();
Once the ShowDialog method is called, you can browse and select a file.
Setting SaveFileDialog Properties
After you place a SaveFileDialog control on a Form, the next step is to set properties.
The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right clicking on a control and selecting Properties menu item. The Properties window looks like Figure 3.
Figure 3
Initial and Restore Directories
InitialDirectory property represents the directory to be displayed when the open file dialog appears the first time.
SaveFileDialog1.InitialDirectory = @"C:\";
If RestoreDirectory property is set to true that means the open file dialog box restores the current directory before closing.
SaveFileDialog1.RestoreDirectory = true;
Title
Title property is used to set or get the title of the open file dialog.
SaveFileDialog1.Title = "Browse Text Files";
Default Extension
DefaultExtn property represents the default file name extension.
SaveFileDialog1.DefaultExt = "txt";
Filter and Filter Index
Filter property represents the filter on an open file dialog that is used to filter the type of files to be loaded during the browse option in an open file dialog. For example, if you need users to restrict to image files only, we can set Filter property to load image files only.
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
FilterIndex property represents the index of the filter currently selected in the file dialog box.
SaveFileDialog1.FilterIndex = 2;
Check File Exists and Check Path Exists
CheckFileExists property indicates whether the dialog box displays a warning if the user specifies a file name that does not exist. CheckPathExists property indicates whether the dialog box displays a warning if the user specifies a path that does not exist.
SaveFileDialog1.CheckFileExists = true;
SaveFileDialog1.CheckPathExists = true;
File Name and File Names
FileName property represents the file name selected in the open file dialog.
textBox1.Text = SaveFileDialog1.FileName;
If MultiSelect property is set to true that means the open file dialog box allows multiple file selection. The FileNames property represents all the files selected in the selection.
this.SaveFileDialog1.Multiselect = true;
foreach(String file in SaveFileDialog1.FileNames) {
MessageBox.Show(file);
}
SaveFileDialog Example
The following code snippet is the code for Save button click event handler. Once a text file is selected, the name of the text file is displayed in the TextBox.
private void SaveButton_Click(object sender, EventArgs e) {
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = @ "C:\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
textBox1.Text = saveFileDialog1.FileName;
}
}
Summary
A SaveFileDialog control allows users to launch Windows Save File Dialog and let them save files. In this article, we discussed how to use a Windows Save File Dialog and set its properties in a Windows Forms application.
-
SaveFileDialog
Class inC#
-
Conclusion
This trivial guide is about using the SaveFileDialog
class in C# to save the file from your C# app to the Windows file storage.
SaveFileDialog
Class in C#
Users can browse the file system and choose which files to save using the SaveFileDialog
component. The dialogue box gives back the name and path of the file that the user selected there.
To write the files to the disc, you must write the code.
Steps for Using the SaveFileDialog
Class
-
The first step is to create a Windows Form Application and add a
SaveFileDialog
control.Using the
SaveFileDialog
class in code at run-time or the Forms designer at design-time, we may create aSaveFileDialog
control. ASaveFileDialog
does not have and is not required to have visual properties like other Windows Forms controls.We can create a
SaveFileDialog
control through either of design view or the explicit code. Let’s have a look at both methods:- Create
SaveFileDialog
through code. The code to create aSaveFileDialog
is:
SaveFileDialog saveDialog = new SaveFileDialog();
The above code will create a
SaveFileDialog
box object. Now, to display this dialog, we use theShowDialog
method:- Create
SaveFileDialog
through Design. Drag and drop aSaveFileDialog
control from the Toolbox to a Form in Visual Studio to create a SaveFileDialog control at design time.
The figure below depicts the
SaveFileDialog
after being dropped by drag and drop onto a Form. - Create
-
The second step is to set some properties of the
SaveFileDialog
. There are different properties available that can be used according to your coding requirements.Setting properties through the Properties Window is the simplest option. The figure below depicts how the Properties window looks.
Different properties can be set in this window. Let’s discuss some of these properties: —
Initial Directory
The
Initial Directory
property specifies the default directory to be opened when the dialog box appears for saving the file. This property can be set from the property window shown above or through the code like this:saveDialog.InitialDirectory = @"D:/New Folder";
Title
The
Title
property sets the title to be displayed on the dialog box that appears for saving the file:saveDialog.Title = "Save Your File Here";
Filter
The
filter
property on a save file dialogue restricts the kinds of files that can be saved using a save file dialogue. For instance, we can specify the Filter option only to save binary .bin files if you wish users to be restricted to them.saveDialog.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*";
These are some properties that can be set for saving the file. There are numerous others, but we will discuss these important ones in this article.
-
After you have set the properties, you can write the code to save the file to disc. For this, the
OpenFile
method is used. This method returns aStream
object that can be used to save the file onto a disc.Stream fileStream; if (saveDialog.ShowDialog() == DialogResult.OK) { if ((fileStream = saveDialog.OpenFile()) != null) { // You can write the code to write the file here. fileStream.Close(); } }
Let’s now sum up the complete code here to save a file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.InitialDirectory = @"C:\Users\user01\OneDrive\Documents";
saveDialog.Title = "Save Your File Here";
saveDialog.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*";
Stream fileStream;
if (saveDialog.ShowDialog() == DialogResult.OK) {
if ((fileStream = saveDialog.OpenFile()) != null) {
// You can write the code to write the file here.
fileStream.Close();
}
}
}
}
}
We have written this code on the click event of a button so that when a button is clicked, the save dialog will open. This will generate the following output:
When we click on the Save File
button, the following popup dialog box will appear:
You can see in the dialog box that the location is set to the “Documents” Folder, and the file type is set to “Bin files.”
Conclusion
Users can start the Windows Save File Dialog and save files using a SaveFileDialog
control. This article discussed using a Windows Save File Dialog and configuring its properties in a Windows Forms application.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Related Article — Csharp GUI
- How to Group the Radio Buttons in C#
- How to Add Right Click Menu to an Item in C#
- How to Add Items in C# ComboBox
- How to Add Placeholder to a Textbox in C#
- How to Simulate a Key Press in C#
The Save File Dialog control (System.Windows.Forms.SaveFileDialog) allows you to save or write data to a specified file. The dialog allows you to browse your file system and pick a directory, then type a filename you want to be the name of the file that will contain the data to be written. You can type the name of the file that exist in the current directory and the dialog can prompt you if you want to overwrite it. You can also type the whole path of a file or directory in the File Name text box located at the bottom of the dialog.
The following table shows some useful properties of the SaveFileDialog control.
Property | Description |
---|---|
AddExtention | Specifies whether to automatically add an extension when the user does not specify a file extension. |
CheckFileExists | Specifies whether to initiate a warning if the user types a file that does not exist. |
CheckPathExists | Specifies whether to initiate a warning if the user types a path that does not exist. |
DefaultExt | The default extensions to add when the user does not indicate a file extension. |
FileName | The file selected by the user. This can also be the default selected the file when the dialog shows up. |
Filter | Allows you to add a filter which are a special string indicating which types or files are only allowed to be opened by the user. |
FilterIndex | If multiple filters are present, this indicates which filter shows as the default starting with index 1. |
InitialDirectory | The initial directory that the OpenFileDialog will show. |
OverwritePrompt | Specifies whether the dialog will prompt you to overwrite a file when an existing file is already found. |
RestoreDirectory | Specifies whether to restore to default directory when the dialog closes. |
Title | The title of the dialog. |
The AddExtention property automatically adds an extension when the user does not indicate the file extension of the file name. The extension to add is specified by the DefaultExt property. The CheckFileExists and CheckPathExists methods are recommended to be set to true so the dialog will issue a warning message if it cannot find the specified file or directory. The InitialDirectory property specifies the initial directory that the dialog will show when you open it up. The Title property is the title of the dialog located at the title bar. The FileName property is the Filename specified by the user.
Specifying File Types
We can specify the file types that the file will have. We use the Filter property which accepts a string containing a special pattern. For example, we can set the dialog to only allow our file to be saved as a text file with .txt file extensions. The Filter property requires a special pattern.
Description1|Extension1|Description2|Extention2|...DescriptionN|ExtentionN
We first start with a description telling about the type of file. We then follow it with a vertical bar (|) followed by the extension. For example, the following pattern allows you to save files as text files.
Text Files|.txt
The description here is Text Files and the extension are .txt. You can specify multiple extensions. For example, the following pattern allows you to save a file as a .txt, or .png.
Text Files|*.txt|Image|*.png
You can select the type that the file will be saved as using the combo box below the File Name text box.
SaveFileDialog Control Example
We will now create an example application that uses the basic capabilities of the SaveFileDialog control. The application will allow a user to type into a multiline text box and then save the text into a text file using a specified file name and path. Please note that we need to import the System.IO namespace in our code.
using System.IO;
Create a form similar to the one below. Use a multiline text box by setting the Multiline property to true. Drag a SaveFileDialog control from the Dialogs category of the Toolbox to the form.
Double-click the button to create an event handler for its Click event. Again, import the System.IO namespace first at the top of the code. Use the following code for the event handler.
private void button1_Click(object sender, EventArgs e)
{
//Specify the extensions allowed
saveFileDialog1.Filter = "Text File|.txt";
//Empty the FileName text box of the dialog
saveFileDialog1.FileName = String.Empty;
//Set default extension as .txt
saveFileDialog1.DefaultExt = ".txt";
//Open the dialog and determine which button was pressed
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//Create a file stream using the file name
FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
StreamWriter writer = new StreamWriter(fs);
//Write the contents of the text box to the stream
writer.Write(textBox1.Text);
//Close the writer and the stream
writer.Close();
}
}
The first line specifies that we can only save our file as a text file with .txt extension. The second one assigns an empty string to the FileName so the File Name text box of the dialog will be initially empty (you can indicate a default filename though). We set the default extension to be .txt so if the user only types the name and forgot or do not include the extensions, the dialog will automatically add the extension name in case no file type is selected. We then open the SaveFileDialog using its ShowMethod property which returns a DialogResult value. The user can now browse the directory where he/she wants to save the file. When the user presses the Save button, then the method ShowDialog will return DialogResult.OK. We tested this using an if statement. We created a FileStreamobject and set the file name and file mode. We then create a StreamWriter object and pass the FileStream object. We use the Writemethod of the writer to write the contents of the text box to the stream and save it to the file. Finally, we close the writer which also closes the file stream.
Execute the application and type anything inside the text box. Click the button and choose a directory. Then type a file name and hit Save. If a similar file exists, you may be prompted if the program should overwrite the file. Setting OverwritePrompt to false will automatically overwrite the file without prompting.
This C# tutorial shows how to use the SaveFileDialog control in Windows Forms.
SaveFileDialog prompts users when saving files.
This control allows the user to set a file name for a specific file. Then you can use the event handling mechanism to add custom code. This writes the file that the user wants to save.
Start. To begin, we create a new Windows Forms Application in Visual Studio. This tutorial requires that you add two separate controls to the blank Windows Form. In the Toolbox pane, double-click on the Button and also the SaveFileDialog icons.
The Button control will be used to open the SaveFileDialog. Like any dialog, you must call the ShowDialog method to open your SaveFileDialog. To add a click event handler to the SaveFileDialog, double-click on the button in the designer.
Button
Also: Double-click on the SaveFileDialog icon in your Visual Studio designer window as well to add the FileOk event handler.
C# program that uses SaveFileDialog using System; using System.ComponentModel; using System.IO; using System.Windows.Forms; namespace WindowsFormsApplication30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // When user clicks button, show the dialog. saveFileDialog1.ShowDialog(); } private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) { // Get file name. string name = saveFileDialog1.FileName; // Write to the file name selected. // ... You can write the text from a TextBox instead of a string literal. File.WriteAllText(name, "test"); } } }
The button1_Click event handler was added, and the saveFileDialog1_FileOk event handler was added. In the button1_Click method, we simply call the ShowDialog method on the saveFileDialog1 instance.
And: This will make the save file dialog appear on the user’s screen when he or she presses the button.
In the saveFileDialog1_FileOk event handler, we handle the user pressing the OK button. At this point, the user wants to actually save the file to the disk. So in this method, we can do actually anything we want.
But: Typically you will want to read the FileName property from the saveFileDialog1 instance.
Then, you can use a file writing method to output data to that location. In this example, I write a string literal «test» to a file. You could read a property such as textBox1.Text and write the string returned by that.
TextBox
Properties. There are lots of properties on the SaveFileDialog control type in Windows Forms. For more details about these, please consult the more detailed MSDN documentation from the smart people at Microsoft.
SaveFileDialog Properties: MSDN
Properties: AddExtension CheckFileExists CheckPathExists CreatePrompt DefaultExt Filter FilterIndex OverwritePrompt RestoreDirectory ShowHelp SupportMultiDottedExtensions ValidateNames
Summary. When developing interactive Windows Forms programs, the SaveFileDialog is useful. This tutorial showed how to add a Button to open the SaveFileDialog, and then actually write to the selected path when the user clicks to save.
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf