Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

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) and the output stream is used for writing into the file
(write operation).

VB.Net I/O Classes

The System.IO namespace has various classes that are used for performing various operations
with files, like creating and deleting files, reading from or writing to a file, closing a file, etc.
The following table shows some commonly used non-abstract classes in the System.IO
namespace −
The FileStream Class

The FileStream class in the System.IO 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 syntax
for creating a FileStream object is as follows –
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)
Example
The following program demonstrates use of the FileStream class
Imports System.IO
Module fileProg
Sub Main()
Dim f1 As FileStream = New FileStream("sample.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 −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

As far as Visual Basic 6 is concerned, there are three modes in which a file can
be accessed.
 1) Text Mode (Sequential Mode)
 2) Random Access Mode
 3) Binary Mode
In the Text Mode, data is ALWAYS written and retrieved as CHARACTERS. Hence, any
number written in this mode will result in the ASCII Value of the number being stored.
For Example, The Number 17 is stored as two separate characters "1" and "7".
Which means that 17 is stored as  [ 49 55 ]  and not as  [ 17 ] .

In the Binary Mode, everything is written and retrieved as a Number. Hence, The


Number 17 Will be stored as  [ 17 ]  in this mode and characters will be represented by
their ASCII Value as always.

One major difference between Text Files and Binary Files is that Text Files support
Sequential Reading and Writing. This means that we cannot read or write from a
particular point in a file. The only way of doing this is to read through all the other
entries until you reach the point where you want to 'actually' start reading. Binary Mode
allows us to write and read anywhere in the file. For example we can read data directly
from the 56th Byte of the file, instead of reading all the bytes one by one till we reach
56.

Just like the Binary Mode, the Random Access Mode allows us to gain instant access
to any piece of information lying anywhere in the file at a cost. In this case, we must
standardize each piece of information. For example, if we need to store a few names in
the file Random Access Mode requires us to mention the length of the 'Names' Field.

Some Names might not fit and for the shorter names the space is inefficiently used.
Random Access Mode allows us to read or write data at a particular record position
rather than a byte position like in Binary Mode.

A Good Example of Sequential Mode is the Audio Cassette. If we have to listen to a


particular Song in the cassette, we have to play the tape right from the beginning until
we reach the beginning of the song. And so obviously, CDs, DVDs etc. are examples of
Binary Mode ( and even Random Access Mode )

III. SEQUENTIAL FILE HANDLING

To open a File in Sequential Mode, we need to use the Open Command like this:

Each File irrespective of its mode requires a file handle(FILE#). All operations on the file
are done using the File Handle. The File Handle can be any number from 1 to 255, and
this number is preceded by the # character.

Files can be opened in three modes in Sequential File Handling Mode and they are used
in different situations as shown.

INPUT -> Used to Read From a File.


OUTPUT -> Used to Write to a File.
APPEND -> Used to Write to a File.

Hence, to open a file Contacts.txt in Input Mode we use the Open Command like this:
Notice that the path of the file is mentioned. If the path is not mentioned, Visual BASIC
assumes the file to be in the current directory. To close the file we use the CLOSE
Command like this:

This Closes the File referred to by File Handle 1. The Close Command can also be called
with no arguments, but in this case it would close all open Files.

NOTE: Closing a File is mandatory after your I/O operations are completed. Not closing
a file can lead to loss of data.

For the rest of this section, assume the Contacts.txt file to contain the following data:

Now let us try to read from this file. We can read each line separately into a string by
using the Line Input Command. Take a look at this snippet:

As you can see, the MessageBox displays:  "Sanchit",9811122233

We can now write a Program that displays the entire contents of a file in a MessageBox,
using the Line Input Command.

The Output is:  "Sanchit",9811122233"Friend",9812345634"Enemy",9821630236


SEQUENTIAL FILE HANDLING EXAMPLES
RDO (Remote Data Objects)

RDO (Remote Data Objects) is an application program interface (API) from Microsoft that
lets programmers writing Windows applications get access to and from both Microsoft and
other database providers. In turn, RDO statements in a program use Microsoft's lower-layer
Data Access Objects (DAO) for actual access to the database. Database providers write to
the DAO interface. RDO has evolved into ActiveX Data Objects (ADO) which is now the
program interface Microsoft recommends for new programs. ADO also provides access to
nonrelational databases and is somewhat easier to use.

What is ADO?

ActiveX Data Objects is a programming model, which means that it is not dependent upon
any given back-end engine. Currently, however, the only engine supporting the ADO model
is OLE-DB. There are many native OLE-DB Providers as well as an OLE-DB Provider for
ODBC.
The ADO object model consists of six objects:

 Connection: Represents an open connection, in this case to an OLE-DB datasource


that can be an ODBC data source, using MSDASQL (the Microsoft OLE-DB provider for
ODBC).
 Error: Contains details about data access errors, refreshed for each time an error
occurs in a single operation involving ADO.
 Command: Defines a specific command you wish to execute against data.
 Parameters: Optional collection off the command object for any parameters you wish
to provide to the command.
 Recordset: Represents a set of records from a table, command object, or SQL Syntax.
Can be created without any underlying Connection object.
 Field: Represents a single column of data in a recordset.
 Property: A collection of values raised by the provider for ADO.
The next two items were new in 2.5:

 Stream: Provides the means to read or write binary information or text.


 Record: Can represent a row in a recordset or a directory or a file.
ADO/R is a subset of this ADO object model used with the Advanced Data Connector that
provides only the Recordset and Field objects.

Installing ADO on your Computer

To properly install ADO on your computer, you need to install MDAC. This installs both ADO
and necessary underlying ADO components. OLE-DB also requires ODBC version 3.0 or later
components.

MDAC is available free for download from the Web at the following URL:

http://msdn.microsoft.com/en-us/data/aa937729.aspx

After ADO is installed on your computer, create a new project inside Visual Basic. From
the Projects menu, choose References, and then select Microsoft ActiveX Data Objects
Library.
The documentation for the ADO Error object indicates that the Errors Collection will be
populated if any error occurs within ADO or its underlying provider. This is somewhat
incorrect. Depending on the source of the error, ADO's errors collection may not be
populated. You need to check both the Visual Basic Error object as well as the ADO Errors
collection.

MORE EXPLANATIONS
ADO (ActiveX Data Object

The ADO (ActiveX Data Object) data control is the primary interface between a Visual Basic application
and a database. It can be used without writing any code at all! Or, it can be a central part of a complex
database management system. This icon may not appear in your Visual Basic toolbox. If it doesn’t, select
Project from the main menu, then click Components. The Components window will appear. Select
Microsoft ADO Data Control, then click OK. The control will be added to your toolbox.

• As mentioned in Review and Preview, previous versions of Visual Basic used another data control. That
control is still included with Visual Basic 6.0 (for backward compatibility) and has as its icon:

Make sure you are not using this data control for the work in this class. This control is suitable for small
databases. You might like to study it on your own.

• The data control (or tool) can access databases created by several other programs besides Visual Basic
(or Microsoft Access). Some other formats supported include Btrieve, dBase, FoxPro, and Paradox
databases.

• The data control can be used to perform the following tasks:

1. Connect to a database.

2. Open a specified database table.

3. Create a virtual table based on a database query.

4. Pass database fields to other Visual Basic tools, for display or editing. Such tools are bound tools
(controls), or data aware.

5. Add new records or update a database.

6. Trap any errors that may occur while accessing data.

7. Close the database.

• Data Control Properties:

Align                                  Determines where data control is displayed.

Caption                              Phrase displayed on the data control.

ConnectionString           Contains the information used to establish a connection to a database.


LockType                        Indicates the type of locks placed on records during editing (default setting
makes databases read-only).

Recordset                       A set of records defined by a data control’s ConnectionString and


RecordSource properties. Run-time only.

RecordSource                  Determines the table (or virtual table) the data control is attached to.

• As a rule, you need one data control for every database table, or virtual table, you need access to. One
row of a table is accessible to each data control at any one time. This is referred to as the current record.

• When a data control is placed on a form, it appears with the assigned caption and four arrow buttons:

Data Access objects (DAO) communicate with Microsoft Access and other ODBC complaint data
sources through the JET engine. They provide properties and methods that allow to perform all the
operation necessary to manage such a system, including the ability to do the following.

Create databases

Define tables, fields, and indexes

Establish relations between tables.

Navigate and query the database, and so on.

You might also like