How Save File Using SaveFileDialog in C#
Submitted by janobe on Thursday, May 23, 2019 - 15:32.
In this tutorial, I will teach you how to save file .txt file using savefiledialog in c#. This method has the ability to save a text file using a SaveFileDialog class. SaveFileDialog is designed to control the file to be saved in the certain directory and it also provides a user-friendly interface to your form. See the procedure below to know how it works.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.
Creating Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application for c#.Step 2
Add a Richtexbox, button and a SaveFileDialog into the form. Do the form just like shown below.Step 3
Press F7 to open the code editor. In the code editor, create a method to save the file in the directory.- private void save_file()
- {
- // instantiate a new class;
- sv = saveFileDialog1;
- //With SaveFileDialog1
- // 'IF THE USER NEGLECTS THE FILE ETENSION THEN, ADD THE DEFUALT EXTENSION.
- sv.AddExtension = true;
- // 'CHECK IF THE OUTPUT PATH ACTUALLY EXISTS
- // 'BEFORE CREATING A NEW FILE AND BEFORE OVERWRITING.
- // 'THE FOLLOWING VALUES ARE IN ITS DEFUALT FORM.
- sv.CheckPathExists = true;
- sv.CreatePrompt = false;
- sv.OverwritePrompt = true;
- sv.ValidateNames = true;
- // 'GET AND SET THE DEFAULT EXTENSION
- sv.DefaultExt = "txt";
- // 'FILLTERING THE FILES THAT YOU HAVE SAVED.
- sv.Filter = "Text files (*.txt)|*.txt|" + "All files|*.*";
- sv.FilterIndex = 1;
- if (sv.ShowDialog() == DialogResult.OK)
- {
- System.IO.File.WriteAllText(sv.FileName, richTextBox1.Text);
- }
- }
Step 4
Write the following code to execute the method that you have created when the button is clicked.- private void button1_Click(object sender, EventArgs e)
- {
- save_file();
- }
Add new comment
- 682 views