Home
C#.WinForms
SaveFileDialog Example
Updated Sep 28, 2022
Dot Net Perls
SaveFileDialog. This prompts users when saving files. This control allows the user to set a file name for a specific file. We use the event handling mechanism to add custom code.
Getting started. Please add a SaveFileDialog to your Windows Forms program in Visual Studio. It can be added directly in the UI through the ToolBox.
OpenFileDialog
An example. The Button control will be used to open the SaveFileDialog. Like any dialog, you must call the ShowDialog method to open your SaveFileDialog.
Note 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.
Detail The button1_Click event handler was added, and the saveFileDialog1_FileOk event handler was added.
Info In the button1_Click method, we call the ShowDialog method on the saveFileDialog1 instance.
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"); } } }
FileOk. Next, in the saveFileDialog1_FileOk event handler, we handle the user pressing the OK button. At this point, the user wants to save the file to the disk.
Info 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 the string "test" to a file.
Tip You could read a property such as textBox1.Text and write the string returned by that.
TextBox
A summary. When developing interactive Windows Forms programs, the SaveFileDialog is useful. We opened a SaveFileDialog, and then wrote to the selected path.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 28, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen