File Handling in VB.net – I/O Classes, FileStream Class in VB.net

What is File Handling in VB.net?

A File Handling in VB.net is a group of data items with a specified name and defined folder location that are kept in computer memory.

In VB.NET, the phrase “File Handling” refers to a variety of actions like opening, creating, reading, writing to, and closing files.

A stream is also produced whenever a file is opened for reading and writing.

A stream is a group of bytes that sends information to a file so it can be read or written.

There are two different types of streams used in VB.NET file handling: read-only input streams and write-only output streams.

VB.net I/O Classes

We use the System.IO namespace in VB.NET, which has numerous classes to carry out various input and output activities with files.

For example, the FileStream class is used to carry out any operation, such as opening, closing, deleting, reading from, or writing to a file.

The following table shows the I/O classes that are commonly used in VB.net programming.

I/O Class in VB.netDescription
FileIt is used to perform some changes in files.
FileInfoIt is used to perform any operation on files.
FileStreamIt is used to apply read or write operations on any location of a file.
BinaryReaderAs the name represents, a Binary reader is used to read primitive data in a binary stream.
BinaryWriterIt is used to write the data in binary format.
DirectoryIt is used to perform some changes or manipulating a directory structure.
DriveInfoIt helps to provide the necessary information for the drive.
BuffredStreamIt is a temporary storage area for the collection of steam bytes.
MemoryStreamIt is used to access stored streaming data in memory.
StreamReaderA StreamReader property is used to read characters from the stream byte.
PathIt is used to perform operations on the path of a file.
StreamWriterA StreamWriter is used to write characters to a stream.
DirectoryInfoIt is used to perform an operation on the directory.
StringReaderIt is used to read string from a string buffer.
I/O Classes in VB.net

FileStream Class in VB.net

The System.IO namespace’s FileStream Class in VB.net facilitates reading from, writing to, and closing files.

The abstract class Stream is where this class originates from.

To create a new file or open an existing file, you need to create a FileStream object.

Syntax of FileStream Class in VB.net:

Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>)

For example, for creating a FileStream object F for reading a file named sampleFile.txt:

Dim f1 As FileStream = New FileStream("sampleFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)

ParameterDescription
FileModeFileShare enumerators have the following members:

Inheritable − It allows a file handle to pass an inheritance to the child processes.

None − It declines to share of the current file.

Read − It allows opening the file for reading.

ReadWrite − It allows opening the file for reading and writing.

Write − It allows opening the file for writing.
FileAccessFileShare enumerators have the following members:

Inheritable − It allows a file handle to pass an inheritance to the child processes.

None − It declines to share of the current file.

Read − It allows opening the file for reading.

ReadWrite − It allows opening the file for reading and writing.

Write − It allows opening the file for writing.
FileShareFileShare enumerators have the following members:

Inheritable − It allows a file handle to pass an inheritance to the child processes.

None − It declines to share the current file.

Read − It allows opening the file for reading.

ReadWrite − It allows opening the file for reading and writing.

Write − It allows opening the file for writing.
FileStream Classes in VB.net

Example program of FileStream Class in VB.net:

Imports System.IO
Module fileProg
   Sub Main()
      Dim f1 As FileStream = New FileStream("sampleFile.txt", _
              FileMode.OpenOrCreate, FileAccess.ReadWrite)
      Dim i As Integer
      For i = 0 To 20
          f1.WriteByte(CByte(i))
      Next i
      f1.Position = 0
      For i = 0 To 20
          Console.Write("{0} ", f1.ReadByte())
      Next i
      f1.Close()
      Console.ReadKey()
   End Sub
End Module

When the above code is compiled and executed, it produces the following result:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

You can test the above example here! ➡ VB.net Online Compiler

Advanced File Operations in VB.net

Simple file operations in VB.net are demonstrated in the preceding example.

However, you must be familiar with the classes’ frequently used properties and methods if you want to take advantage of their enormous capability.

1. StreamReader and StreamWriter in VB.net

A text can be read from a text file using the StreamReader classin VB.net and written to a specific text file using the StreamWrite file in VB.net.

The Abstract base class stream, which represents a reader who can read a sequence of characters and a writer who can write a series of characters, is where these Stream classes derive from.

Example Program of StreamReader Class in VB.net:

sampleFile.txt

IT Source Code Programmers:
-Glenn
-Ted Ted
-Adones
-Jude

Imports System.IO
Module StReader
    Sub Main()
        ' Create St as an object of StreamReader Class  
        Dim St As StreamReader = New StreamReader("C:\Users\Lenovo\Desktop\sampleFile.txt")
        Dim ln As String
        ' It reads and prints the content from Myfile.txt  
        ln = St.ReadLine()
        While (ln <> Nothing)
            Console.WriteLine(ln)
            ln = St.ReadLine()
        End While
        St.Close()
        Console.ReadKey()
    End Sub
End Module

When the above code is compiled and executed, it produces the following result:

IT Source Code Programmers:
-Glenn
-Ted Ted
-Adones
-Jude

You can test the above example here! ➡ VB.net Online Compiler

Example program of StreamWriter Class in VB.net:

Imports System.IO
Module StWriter
    Sub Main()
        Dim ln As String
        ' Create a path for Mytext.txt file to insert the below data.   
        Dim St As StreamWriter = New StreamWriter("C:\Users\Lenovo\Desktop\writer.txt")
        St.WriteLine(" Welcome To IT SOURCECODE!")
        St.WriteLine(" VB.NET is the Programming language")
        St.WriteLine(" Learn VB.NET File Handling")
        St.Close()

        ' Read and print the data from the specified file.  
        Dim sw As StreamReader = New StreamReader("C:\Users\Lenovo\Desktop\writer.txt")
        ln = sw.ReadLine()
        While (ln <> Nothing)
            Console.WriteLine(ln)
            ln = sw.ReadLine()
        End While
        sw.Close()
        Console.WriteLine("Press any key to exit...")
        Console.ReadKey()
    End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Welcome To IT SOURCECODE!
VB.NET is the Programming language
Learn VB.NET File Handling
Press any key to exit…

Further, we can also check if the file “writer.txt” is created on the defined route “C:\Users\Lenovo\Desktop\writer.txt” or not.

When we follow the defined path, it shows the following content in writer.txt file.

StreamWriter Class
StreamWriter Class

You can test the above example here! ➡ VB.net Online Compiler

2. BinaryReader and BinaryWriter Classes in VB.net

Binary streams employ the BinaryReader and BinaryWriter classes in VB.net.

The internal binary format of binary data is used for reading and writing; these binary data cannot be read by humans.

Binary data can be read from files using the BinaryReader class, and text can be written to specific binary files using the BinaryWriter file.

Example program of BinaryReader Class in VB.net:

Imports System.IO
Module BinReader
    Sub Main()
        Dim FS As FileStream = New FileStream("C:/Users/Lenovo/Desktop/binary.txt", FileMode.Open, FileAccess.Read)
        Dim binReader As New BinaryReader(FS)
        Dim a As Integer = binReader.ReadInt32()
        Dim c As Char = binReader.ReadChar()
        Dim f As Single = binReader.ReadSingle()
        Console.WriteLine("Integer is {0}", a)
        Console.WriteLine("Char data is {0}", c)
        Console.WriteLine(" Float data is {0}", f)
        binReader.Close()
        FS.Close()
        Console.WriteLine(" Press any key to exit...")
        Console.ReadKey()
    End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Integer is 1818580759
Char data is c
Float data is 1.9433263E-19
Press any key to exit…

You can test the above example here! ➡ VB.net Online Compiler

Example program of BinaryWriter Class in VB.net:

Imports System.IO
Module BinWriter
    Sub Main()
        Dim FS As FileStream = New FileStream("C:/Users/Lenovo/Desktop/binary.txt", FileMode.OpenOrCreate, FileAccess.Write)
        Dim binWriter As New BinaryWriter(FS)
        Dim name As String = "Welcome to ITSOURCECODE"
        Dim db As Double = 1010
        Dim age As Integer = 10111
        binWriter.Write(name)
        binWriter.Write(db)
        binWriter.Write(age)
        binWriter.Close()
        FS.Close()
        Console.WriteLine(" Press any key to exit...")
        Console.ReadKey()
    End Sub
End Module

You can test the above example here! ➡ VB.net Online Compiler

3. FileInfo Class in VB.net

The FileInfo class in VB.net is used to retrieve file attributes including name, size, copying, and moving history.

The FileInfo class, which is descended from the FileSystemInfo class, aids in the creation of a FileStream object.

Example Program of FileInfo Class in VB.net:

Imports System.IO
Module GetFilename
    Sub Main()
        Dim mk As DirectoryInfo = New DirectoryInfo("C:/Users/Lenovo/Desktop/VBfolder")
        Dim fl As FileInfo() = mk.GetFiles()
        Dim f As FileInfo
        For Each f In fl
            Console.WriteLine(" Name of File: {0} Size: {1} Creation time: {2} Extension of file is :{3}", f.Name, f.Length, f.CreationTime, f.Extension)
        Next f
        Console.WriteLine("Press any key to exit...")
        Console.ReadKey()
    End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Name of File: binary.txt Size: 36 Creation time: 02/07/2022 2:20:19 pm Extension of file is :.txt
Name of File: sampleFile.txt Size: 61 Creation time: 02/07/2022 1:27:01 pm Extension of file is :.txt
Name of File: writer.txt Size: 94 Creation time: 02/07/2022 1:53:53 pm Extension of file is :.txt
Press any key to exit…

You can test the above example here! ➡ VB.net Online Compiler

Summary

We read and write (mutate) files using concise code, such as the Using statement.

We work with text files a lot. However, similar operations can also be applied to binary data or pictures.


Leave a Comment