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.

savefiledialog

savefiledialog

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

savefiledialog

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.

savefiledialog

savefiledialog

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.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *