How to Open a File in Visual Basic


One of the first things you learn in programming is how to write to a file and how to open the same file to read its contents. Transferring information from a Visual Basic application to a file is very common in the programming world. You may want to save user settings or other information such as results from your program. In Visual Basic you can use the "File.Open" method to open a file with read or write access.

  • Launch "Microsoft Visual Basic Express," and click the "New Project" on the "Start Page" tab. Click "Visual Basic" below "Installed Templates," and double-click "Console Application" to create a new console project.

  • Declare the following namespaces in the declarations area of your module:

    Imports System

    Imports System.IO

    Imports System.Text

  • Copy and paste the following code below "Sub Main()" to create a temporary file with some text:

    Dim filePath As String = Path.GetTempFileName()

        Dim fileStream As FileStream = File.Open(filePath, _

    FileMode.Open, _

    FileAccess.Write, _


    Dim writeInfo As Byte() = New UTF8Encoding(True).GetBytes("Write data to file.")

    fileStream.Write(writeInfo, 0, writeInfo.Length)


  • Copy and paste the following to open the file created in the previous step and display the contents through the console window:

        fileStream = File.Open(filePath, FileMode.Open)

    Dim byteInfo(1024) As Byte

    Dim tmpStr As UTF8Encoding = New UTF8Encoding(True)

    Do While fileStream.Read(byteInfo, 0, byteInfo.Length) > 0





  • Press "F5" to run the program and display a message box with the contents of the file.

Related Searches


  • Photo Credit John Foxx/Stockbyte/Getty Images
Promoted By Zergnet


Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!