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
public partial class Form1 : Form
private void button1_Click(object sender, EventArgs e)
// When user clicks button, show the dialog.
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.
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
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.