Basic opening and reading files in VB.NET

File opening and reading into a form seems to be a bit of a tricky feat for the beginner VB.NET programmer. Along with all this is the open file dialog which could use some basic understanding as well. How does a beginner create it, configure it and show it to the user ? In this entry we will attempt to put a basic file opening and reading mechanism in place that can help anyone get up and running with this basic operation. Next thing you know, you will be opening Word documents faster than a crack addict on a dime sack. All this in the next entry of the Programming Underground!

The process of creating a file open dialog and configuring it to select specific types of files is quite simple really. If you know how to set it up. First before we start with the code, we need to remember to import the System.IO namespace anytime we are dealing with files. This namespace is going to allow us to use file related functions and class types like Filestream. All which will be needed to open files and read from them.

The next thing we need to do is either add an openfiledialog control to our form or create one in code. Our example below creates one in code using a variable called MyFileDialog and the new keyword. We instantiate a new variable using the OpenFileDialog class and then move onto the next step of configuring it. Before we show it to the user we want to put our own special touches on it including a custom title and tell the dialog which file extensions we want to see. In our example we give the dialog a title of “Open a text file example” and we setup the filter property to allow only text files with the extension “.txt” to be seen. The last option we configure is the filename property which is the name they see in the file name text box. Here we set it to blank and hopefully force the user to type in a file name.

Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

	 ' Create a new open file dialog
	 Dim MyFileDialog As New System.Windows.Forms.OpenFileDialog

	 ' Configure the dialog to show only text files
	 ' Set its title and set the filename field blank for the moment.
	 MyFileDialog.Filter = "Text File (*.txt)|*.txt"
	 MyFileDialog.Title = "Open a text file example"
	 MyFileDialog.FileName = ""
	 ' Show the dialog and see if the user pressed ok.
	 If MyFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then

		  ' Check to see if they selected a file and that it exists.
		  If File.Exists(MyFileDialog.FileName) Then
			   Dim strFile As String = MyFileDialog.FileName
			   Dim reader As StreamReader

					' Setup a file stream reader to read the text file.
					reader = New StreamReader(New FileStream(strFile, FileMode.Open, FileAccess.Read))

					' While there is data to be read, read each line into a rich edit box control.
					While reader.Peek > -1
						 richtextbox1.Text &= reader.ReadLine() & vbCrLf
					End While

					' Close the file
			   Catch ex As FileNotFoundException
					' If the file was not found, tell the user.
					MessageBox.Show("File was not found. Please try again.")
			   End Try
		  End If
	 End If
End Sub

Now that we have the open file dialog window configured, we show it using the showdialog() method. This function shows the dialog in modal mode which forces the user to then choose a file and either hit ok, cancel or close the window. In either case we check to make sure they chose ok by comparing it against the OK dialog result enumeration value.

Once they have chosen ok, we check the filename to make sure it exists. This is a tad bit different than something like a save dialog where the filename may be new and not exist yet. The open dialog can reasonably assume that the file they type is one that already exists, but we check to make sure using the File object’s exists() function. If they typed in something or somehow chose a file that doesn’t already exist, the code will just close and nothing will be loaded.

After validating the result of the dialog, that they pressed ok, and that a filename was chosen we attempt to open the file by first creating a StreamReader. All files that you open, all data that comes from a keyboard or goes to screen or printer are called “streams” as in streams of data. The best way to think of a stream is like a river of data. You can open up a dam, let the data flow and scoop out data using reading methods. A stream reader is one of those such mechanisms. In order to setup the streamreader, we have to let it know that we are reading a file stream, so we use the filestream object to open the file in read mode (versus write mode).

If this opening of the stream fails, like the file is not found, it would trip off our error catching and print a message saying that the file is not found. But if it succeeds, we then go to the process of reading the file. We chose to use a while loop which peeks at the stream to see if there is data to be read. If there is, the value will be greater than -1 and we read a line out of the text file using the streamreader’s readline() function. We then add this line to the richtextbox along with a carriage return at the end. We keep looping through the lines of the file and adding them to the richtextbox until peek returns a -1 and tells our loop that there is no more to be read.

We then close the file and finish the event. The result is a richtextbox which has all the lines of the textfile loaded into it. You may see various processes of loading files into controls, but this is a nice simple straight forward method of selecting a text file using the openfiledialog control and a simple while loop for reading.

Keep in mind that this example is primarily designed to be used on text files and may only partially work with Microsoft Word files (.doc files). It doesn’t keep track of formatting so you will have to choose how you want to format the content. It does form a good foundation for further modifications and formatting of data.

So I hope you find the little snippet useful and the content pretty straight forward and on the money. An example you could do to make this even more robust is to check the file extension and verify that it is a text file and not some other file the user typed in. Try that on your own and see what you get!

Hopefully you found this snippet useful and thank you for reading. 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.