How Save File Using SaveFileDialog in C#

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.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Add a Richtexbox, button and a SaveFileDialog into the form. Do the form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, create a method to save the file in the directory.
  1.  
  2. private void save_file()
  3. {
  4. // instantiate a new class;
  5. SaveFileDialog sv = new SaveFileDialog();
  6. sv = saveFileDialog1;
  7.  
  8. //With SaveFileDialog1
  9. // 'IF THE USER NEGLECTS THE FILE ETENSION THEN, ADD THE DEFUALT EXTENSION.
  10. sv.AddExtension = true;
  11.  
  12.  
  13. // 'CHECK IF THE OUTPUT PATH ACTUALLY EXISTS
  14. // 'BEFORE CREATING A NEW FILE AND BEFORE OVERWRITING.
  15. // 'THE FOLLOWING VALUES ARE IN ITS DEFUALT FORM.
  16. sv.CheckPathExists = true;
  17. sv.CreatePrompt = false;
  18. sv.OverwritePrompt = true;
  19. sv.ValidateNames = true;
  20.  
  21. // 'GET AND SET THE DEFAULT EXTENSION
  22. sv.DefaultExt = "txt";
  23.  
  24. // 'FILLTERING THE FILES THAT YOU HAVE SAVED.
  25. sv.Filter = "Text files (*.txt)|*.txt|" + "All files|*.*";
  26. sv.FilterIndex = 1;
  27.  
  28. if (sv.ShowDialog() == DialogResult.OK)
  29. {
  30. System.IO.File.WriteAllText(sv.FileName, richTextBox1.Text);
  31. }
  32. }

Step 4

Write the following code to execute the method that you have created when the button is clicked.
  1.  
  2. private void button1_Click(object sender, EventArgs e)
  3. {
  4. save_file();
  5. }
  6.  
For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment