ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)