• We just launched and are currently in beta. Join us as we build and grow the community.

File Handling: Writing and Saving a Text File

Tigerwoods09

Forum Architect
Divine
T Rep
0
0
0
Rep
0
T Vouches
0
0
0
Vouches
0
Posts
136
Likes
188
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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:

save1.png


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. Try
  12. 'gets a string containing the filename selected in the dialog box
  13. myStreamWriter =

    System.

    IO

    .

    File

    .

    AppendText

    (

    SaveFileDialog1.

    FileName

    )
  14. 'it writes the string to stream
  15. myStreamWriter.

    Write

    (

    RichTextBox1.

    Text

    )
  16. 'clears all buffers for the current writer and causes any
  17. 'buffered data to be written to the underlying stream
  18. myStreamWriter.

    Flush

    (

    )
  19. Catch

    ex As

    Exception
  20. 'catch unnecesary errors
  21. MsgBox

    (

    ex.

    Message

    )

  22. End

    Try

When you execute the code above, it will look like as shown below.

save2_0.png


 

452,292

323,340

323,349

Top