File Handling: Writing and Saving a Text File

This tutorial is a continuation of our previous tutorial called “File Handling: How to Open a Text File in Visual Basic”. But this time we’re going to focus on how to create and save a text file. To start in this lesson, open our previous project named “FileHandling”. Then, we’re going to add another sub menu called “save” and we need also to add another control named SaveFileDialog from the toolbox. This will look like as shown below: At this time, double click the save sub menu and add the following code: In this code we use a StreamWriter class that inherits from the abstract class TextWriter that represents a writer, meaning it is able to write a series of character.
  1. 'call the savefiledialog
  2. SaveFileDialog1.ShowDialog()
  3. 'we use StreamWriter for writing characters to a stream
  4. Dim myStreamWriter As System.IO.StreamWriter
  5. 'we set default for savefiledialog filter
  6. SaveFileDialog1.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
  7. 'set the checkpath to true
  8. SaveFileDialog1.CheckPathExists = True
  9. 'set the Savefiledialog title
  10. SaveFileDialog1.Title = "Save File"
  11.  
  12. Try
  13. 'gets a string containing the filename selected in the dialog box
  14. myStreamWriter = System.IO.File.AppendText(SaveFileDialog1.FileName)
  15. 'it writes the string to stream
  16. myStreamWriter.Write(RichTextBox1.Text)
  17. 'clears all buffers for the current writer and causes any
  18. 'buffered data to be written to the underlying stream
  19. myStreamWriter.Flush()
  20. Catch ex As Exception
  21. 'catch unnecesary errors
  22. MsgBox(ex.Message)
  23.  
  24. End Try
When you execute the code above, it will look like as shown below.

Add new comment