File Handling: How to Open a Text File in Visual Basic.NET

In this tutorial, I’m going to show you how to open a text file using Visual Basic. A text file is considered as a plain text and the only capable of creating plain text files and save it to .txt extension is notepad. So to start with this tutorial, open first a visual basic and create a project named “FileHandling”.

Then on the form, add a MenuStrip from a toolbox, and a RichTextBox. Next, we’re going to add a menu to our menu strip such as “File” and under “File”, add “Open” as a sub-menu and change the text property to “menuOpen”. And finally, Set the Dock property of RichTextBox into “Fill”. And when you execute this application it should look like as shown below:

At this time, we’re going to add functionality to our application, to do this, double click the “Open” Submenu. And add the following code:

  1. 'declare open as new openFiledialog so that when the Open Submenu is click,
  2. 'the OpenfileDialog will appear.
  3. Dim Open As New OpenFileDialog()
  4. 'it is declared as System input and output Streamreader
  5. 'it reads characters from a byte stream in a particular encoding
  6. Dim myStreamReader As System.IO.StreamReader
  7. 'in an open dialog box, it will give an opening filter for the current filenames,
  8. 'or the save file types.
  9. Open.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
  10. 'it checks if the file exists or not
  11. Open.CheckFileExists = True
  12. 'sets the openfile dialog name as "OpenFile"
  13. Open.Title = "OpenFile"
  14. Open.ShowDialog(Me)
  15.  
  16. Try
  17. 'it opens the selected file by the user
  18. Open.OpenFile()
  19. 'opens the existing file
  20. myStreamReader = System.IO.File.OpenText(Open.FileName)
  21. 'it reads the streams from current position to the end of position and display the result to RichTextBox as Text
  22. RichTextBox1.Text = myStreamReader.ReadToEnd()
  23. Catch ex As Exception
  24. 'it will catch if any errors occurs
  25. MsgBox(ex.Message, MsgBoxStyle.Information)
  26. End Try

The code above uses a StreamReader. The StreamReader is an object available to System.IO to read streams of text. The stream is basically the sequence of bytes passing through the communication path. Then two main streams are the input stream that is used for reading data from file (read operation) and the output stream is used for writing into a file (write operation).

That's the end of this tutorial, I hope this will help you with what you are looking for and for your future projects.

Enjoy Coding :)

Add new comment