C# SaveFileDialog ExampleUse the SaveFileDialog control in Windows Forms. Call ShowDialog and access FileName.
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.
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. To add a click event handler to the SaveFileDialog, double-click on the button in the designer.
Also Double-click on the SaveFileDialog icon in your Visual Studio designer window as well to add the FileOk event handler.
Click The button1_Click event handler was added, and the saveFileDialog1_FileOk event handler was added.
Info 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.
Next, 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.
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"); } } }
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.
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.
© 2007-2021 sam allen. see site info on the changelog