VB.Net File Handling
A file is a collection of data on a disc that has a unique name and a directory path. When a file is opened for reading or writing, it is transformed into a stream.
The stream is essentially a sequence of bytes traversing the communication route. The input and output streams are the two main streams. The input stream is used to read data from the file (read operation), and the output stream is used to write data into the file (write action) (write operation).
VB.Net I/O Classes
The System.IO namespace contains classes for performing different file operations like creating and deleting files, reading from or writing to a file, closing a file, and so on.
The table below lists some of the most often used non-abstract classes in the System.IO namespace.
I/O Class |
Description |
BinaryReader |
Reads primitive data from a binary stream. |
BinaryWriter |
Writes primitive data in binary format. |
BufferedStream |
A temporary storage for a stream of bytes. |
Directory |
Helps in manipulating a directory structure. |
DirectoryInfo |
Used to perform operations on directories. |
DriveInfo |
Provides information for the drives. |
File |
Used for manipulating files. |
FileInfo |
For performing operations on files. |
FileStream |
Used to read and write to any location in a file. |
MemoryStream |
Used for random access of streamed data stored in memory. |
Path |
Performs operations on path information. |
StreamReader |
Used for reading characters from a byte stream. |
StreamWriter |
It is used for writing characters to a stream. |
StringReader |
It is used for reading from a string buffer. |
StringWriter |
It is used for writing into a string buffer. |
The FileStream Class
The System.IO namespace's FileStream class aids in reading from, writing to, and closing files. This class is a subclass of the abstract class Stream.
To create a new file or open an existing one, you must first create a FileStream object. The following is the syntax for creating a FileStream object −
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 sample.txt −
Dim f1 As FileStream = New FileStream("sample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Parameter |
Description |
FileMode |
The FileMode enumerator defines several file-opening mechanisms. The FileMode enumerator's members are as follows:
|
FileAccess |
FileAccess enumerators have members: Read, Write, ReadWrite. |
FileShare |
Listed below are the members of FileShare enumerators −
|