File Handling: Writing and Saving a Text File

Submitted by: 
Visitors have accessed this post 2675 times.

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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.