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.
Please add a SaveFileDialog
to your Windows Forms program in Visual Studio. It can be added directly in the UI through the ToolBox
.
The Button
control will be used to open the SaveFileDialog
. Like any dialog, you must call the ShowDialog
method to open your SaveFileDialog
.
SaveFileDialog
, double-click on the button in the designer.Double
-click on the SaveFileDialog
icon in your Visual Studio designer window as well to add the FileOk
event handler.button1_Click
event handler was added, and the saveFileDialog1_FileOk
event handler was added.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.
FileName
property from the saveFileDialog1
instance.string
"test" to a file.textBox1.Text
and write the string
returned by that.When developing interactive Windows Forms programs, the SaveFileDialog
is useful. We opened a SaveFileDialog
, and then wrote to the selected path.