File Handling: How to Open a Text File in Visual Basic
In this tutorial I’m going to show you how to 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” Sub menu. And add the following code:
- 'declare open as new openFiledialog so that when the Open Sub menu is click,
- 'the OpenfileDialog will appear.
- Dim Open As New OpenFileDialog()
- 'it is declare as System input and output Streamreader
- 'it reads characters from byte stream in a particular encoding
- Dim myStreamReader As System.IO.StreamReader
- 'in an open dialog box, it will give an opening filter for the current filenames,
- 'or the save file types.
- Open.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
- 'it checks if the file is exist or not
- Open.CheckFileExists = True
- 'sets the openfile dialog name as "OpenFile"
- Open.Title = "OpenFile"
- 'it opens the selected file by the user
- 'opens the existing file
- myStreamReader = System.IO.File.OpenText(Open.FileName)
- 'it reads the streams from current position to the end of position and display the result to RichTextBox as Text
- RichTextBox1.Text = myStreamReader.ReadToEnd()
- Catch ex As Exception
- 'it will catch if any errors occurs
- MsgBox(ex.Message, MsgBoxStyle.Information)
- 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).