Chapter Five
Manipulating Files
Introduction
• 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 (read operation)
• the output stream is used for writing into the file (write operation)
Opening text file in VB
• The first step in working with files in Visual Basic is to open the file
• This is achieved using the Visual Basic FileStream class
• The FileStream class in the [Link] namespace helps in reading from, writing to
and closing files
• This class derives from the abstract class Stream
• You need to create a FileStream object to create a new file or open an existing file
• The FileStream constructor accepts the file name to be opened followed by a
number of other parameters defining the mode in which the file is to be opened
• These fall into the categories of FileMode, FileAccess and FileShare
FileMode options
FileAccess options
FileShare options
Cont.
• With the above options in mind, the following code excerpt opens
‘E:\[Link]' in [Link] with [Link]
permission and no file sharing, and then closes it:
Write to a file
• Once a file has been opened it can be written to using the Visual Basic
StreamWriter class
• The StreamWriter constructor takes a FileStream as the sole parameter
• The Write() and WriteLine() methods of the StreamWriter class are then used to
write to the file.
• Write() writes the text with no new line appended to the end of each line.
• WriteLine() on the other hand, appends a new line to end of each line written to
the file.
Cont.
Cont.
Read from a file
• Read some data from the file is achieved using the Visual Basic StreamReader
object
• The StreamReader ReadLine() method can be used to read the next line from the
file stream including the new line.
• The ReadToEnd() method can be used to read from the current line in the file to
the end of the file
Cont.
Cont.
ReadLine()
How to update text file
The file mode have to be [Link] and file access is [Link]
Cont.
How to copy a file
How to move a file
Deleting file