File Handling
File Handling
A file is a collection of data stored in a disk with a specific name and a directory path. When a file
is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There are
two main streams: the input stream and the output stream. The input stream is used for
reading data from file readoperation and the output stream is used for writing into the file
writeoperation.
The following table shows some commonly used non-abstract classes in the System.IO
namespace:
You need to create a FileStream object to create a new file or open an existing file. The syntax for
creating a FileStream object is as follows:
Parameter Description
FileMode
The FileMode enumerator defines various methods for opening files. The
members of the FileMode enumerator are:
Append: It opens an existing file and puts cursor at the end of file, or
creates the file, if the file does not exist.
Truncate: It opens an existing file and truncates its size to zero bytes.
FileAccess
FileAccess enumerators have members: Read, ReadWrite and Write.
FileShare
FileShare enumerators have the following members:
Example:
The following program demonstrates use of the FileStream class:
Imports System.IO
Module fileProg
Sub Main()
Dim f1 As FileStream = New FileStream("test.dat", _
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
We will discuss these classes and the operations they perform in the following sections. Please
click the links provided to get to the individual sections:
It involves reading from and writing into text files. The StreamReader and StreamWriter
classes help to accomplish it.
It involves reading from and writing into binary files. The BinaryReader and BinaryWriter
classes help to accomplish this.
It gives a VB.Net programmer the ability to browse and locate Windows files and directories.
Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js