ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Visual Basic Write to Text File Example

Updated on February 7, 2016

Write To Text File Example Layout

In this example we are going to use a simple multi line text box that will allow the user to type in to the text box values and then save them to a text file. To keep the code relevant to the actual writing to the text file we will use a simple button to create a file on your hard drive in order to save text to the file.

Getting Started - Set Up The Write Text To Text File Example

  1. Create yourself a new Windows forms application and name it WriteTextToTextFileExample
  2. Add a text box and 3 buttons to your Form and lay them out as in the picture below. (See the control reference below for names and settings)

Once you have all the controls set out on the Winform be sure to save your Application.

The process behind this text file example is firstly check if there is a file on your hard drive to write to, for ease we will use the same one and have the form check for the file and if it has been removed we will create it when the form loads.

Then we will have 2 modes, first button will append text to the text file and the second will completely re write the text file

Write Text Example - Control Reference

Below are the controls added for this text file example, and the properties I have changed for this project

Form1

  • Text = "Write Text To Text File Example"
  • Size = 600, 400

TextBox1

  • Name = mainTextBox
  • MultiLine = true
  • size = 560, 300

Button1

  • Name = closeButton
  • Text = "Close"

Button2

  • Name = updateButton
  • Text = "Update"

Button3

  • Name = saveAllButton
  • Text = "Save All"

NOTE: You can name your controls as you wish however if you change from the settings listed you will need to modify the names in the code should you copy and paste the code in to your application to avoid errors when running your application

Write Text File Example - Form Layout

Text File Example - Code Break Down

Below is the full version of the code you can copy and paste in to your text file example, here is the code as I write it giving help on what is going on to aid in understanding what we are doing in each part.

Be sure to add the 2 Import statements as seen in line 1 and 2 of the code below

Step 1 - Check and Create a Text File

I opted to do this in the Form Load event of the program this will ensure that we have the file available and save any errors in the future, it will also gives us the chance to do a check and create or not create depending on the returned value.

To add the code double click on the Form to generate the "FormLoad" event handler and inside that code block we do the following

  • Check if the file exists using a boolean (FileExists) (See Line 3 for the Declaration)
  • If FileExists = True then we simply let the form load
  • if FileExisits we create a new Text File on the hard drive.

That's it, now ever time we load this form the program will check for a File called myTextFile.txt and if it doesn't find it it will create it see points below!

Notes: when you write the above code ensure the letter of your hard drive is C if it isn't then modify the code by adding the letter assigned to your hard drive in place of the C (you can check his in my computer)

Ensure you place the .dispose command after you create file command to ensure that the program disposes of the use and allows it to be accessed in other parts of the program remember when writing, reading or creating text files you must close or dispose of the object that is using it, else you will not be able to access that Text File in other parts of your program.

Step 2 - Update Text File


Our update button will create a SteamWriter and append text to the file and a new line so that we have a nice flow much like a list of text. To avoid duplicating text once we have written the text box contents to the file we will also clear the text box ready for new text

For the update to work, we need to use the statement in line 24 which is a using statement, if we use a simple streamwriter and tell it to write to that text it will replace what is already in there (see the Step 3 below)

Also ensure that once you have finished writing the text you close your streamwriter, and finish with the End Using statement

Line 33 allows us to clear the text box ready for new text to be added to the text file.

Step 3 - Save All Text

In this step we deal with the save all button, again using the button click event, and while this is pretty much the same as step 2 there is 1 slight difference, using this button will clear all of the text in the text file and copy what is in the text box only.

If you take a closer look at line 24 and line 38 in the code where we create the stream writer you will see for the second one (line 38) we do not use the Using keyword so each time we click the Save All button it takes the file as a new text file and "re creates it" to show only what is in the text box.

Also note there is no End Using statement at the bottom of the Save All button code

Step 4 - Close Button

And finally we code the close button this could be coded to have an "auto save" feature but for this example we simply want to be able to exit the program so we use the Me.Close() statement in order to simply exit the program.

See below for the full code as copied from my working example, I hope this helps you achieve some more function in your applications and helps you understand a little bit more about creating and writing to text files.

Write Text File Example - Full Code

Imports System
Imports System.IO
Public Class Form1

    Dim FileExists As Boolean = False

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        'Check that the text file called myTextFile is available
        FileExists = System.IO.File.Exists("C:\myTextFiles\MyTextFile.txt")

        'Check the outcome of the above - we only need to know if it is false (file doesn't exist)
        If FileExists = False Then
            'if the file isnt there then create the file (ensure you use the .dispose on the end)
            'If you do not have the .dispose on the end you cannot access the file to write to it.
            System.IO.File.Create("C:\myTextFiles\MyTextFile.txt").Dispose()
        End If

    End Sub

    Private Sub updateButton_Click(sender As Object, e As EventArgs) Handles updateButton.Click

        ' create a new streamwriter and point it to the text file
        Using myWriter As StreamWriter = File.AppendText("C:\myTextFiles\MyTextFile.txt")

            'tell our streamwriter to append text to the file
            myWriter.WriteLine(mainTextBox.Text)

            'close the streamwriter
            myWriter.Close()

            'clear the contents of the textbox
            mainTextBox.Clear()
        End Using
    End Sub

    Private Sub saveAllButton_Click(sender As Object, e As EventArgs) Handles saveAllButton.Click
        Dim myWriter As New System.IO.StreamWriter("C:\myTextFiles\MyTextFile.txt")
        'tell our streamwriter to append text to the file
        myWriter.WriteLine(mainTextBox.Text)

        'close the streamwriter
        myWriter.Close()

        'clear the contents of the textbox
        mainTextBox.Clear()
    End Sub

    Private Sub closeButton_Click(sender As Object, e As EventArgs) Handles closeButton.Click
        Me.Close()
    End Sub
End Class

How to Write Text To Text Files - Conclusion

This example was to show how to add text or rewrite the text file using basic code, here we have been able to create a way to update text to a text file and also clear the contents of a text file in order to write new text.

If you have any issues please leave your comments below and I will answer as best I can, also feel free to contact me on Facebook, I will happily help people out where I can. While I get my hubs written up if you need code to do something specific please feel free to ask, and if possible I will write an example program to help you out as my next project.

Thanks for reading be sure to check out my other examples and follow me for more great examples on how to become a VB coder!

Your Feedback

Was This Example Helpful?

See results

Have Your Say

    0 of 8192 characters used
    Post Comment

    No comments yet.