Sunday, August 9, 2015

File Handling in VB.NET



Today we will look in to file handling in VB.NET.
File handling in VB.NET is not hard to understand and learn because it is very similar to file handling in other programming languages. Though the syntax of the language is different from most of the programming languages.

There are many VB.NET I/O stream classes available.

  • BinaryReader - Reads primitive data from a binary stream
  • BinaryWriter - Wrires primitive data in binary format
  • StreamReader - Used to read characters from a byte stream
  • StreamWriter - Used to write characters to a byte stream
There are many other I/O classes available for various purposes.

In order to handle files (read or write to) we have to import the IO class first as follows.

Imports System.IO

Now environment to read and write to files is set.

Let's read from a file to our VB.NET program.
In order to do this we have to create a new object from StreamReader class as shown below.

Dim readObject As New StreamReader("E:/new file.txt") 

StreamReader object needs a one argument in order to create the object. The argument should contain the file path that we need to read from.

Now we can read the file using methods available in the StreamReader class through the object  that we have created recently as follows.


 Dim read As String = readObject.ReadToEnd()
 Dim readFile As String = readObject.ReadLine()

There are many methods available that we can use, above shown are two methods available in the class.

Let's write to a file from our VB.NET program.
In order to do this we have to create an object from StreamWriter class as shown below.

Dim writeObject As New StreamWriter("E:/new file.txt", True)

StreamWriter object needs two arguments to create an object.One argument is same as the StreamReader, it requires the file path that we want to write to. Other argument is true or false. If it is true StreamWriter will append the file. If other argument is false StreamWriter will replace the contents of the file. The default argument is set to false.

writeObject.Write("This text will be written to the file")
writeObject.WriteLine("This text line will be written to the file")

After writing to a file always remember to use the flush method.

writeObject.flush()

With using this method that we can be sure that all the changes that we have done to the file have saved to the hard drive of the computer. Otherwise the changes that are still recorded in the RAM will not be saved to the file.

After opening a file (to read or write to) always remember to close the file. Otherwise it will use the system resources even after the program is closed or when we do not need them.
You can close the file using close() command as follows.

writeObject.close()

Past Topics:-
Like Us on Facebook:-



Comment box is open for your Ideas, Suggestions, Comments and Complaints...!