Wednesday, January 23, 2008

Lesson 14: Working with Files

14.1 Introduction

Up until lesson 13 we are only creating programs that could accept data at runtime, when a program is terminated, the data also disappear. Is it possible to save data accepted by a VB
program into a storage device, such as a hardisk or diskette, or even CDRW? The answer is possible. Is this chapter, we will learn how to create files by writing them into a storage device and then retrieve the data by reading the contents of the files using customized VB programs.

14.2 Creating files

To create a file , use the following command

Open "fileName" For Output As #fileNumber

Each file created must have a file name and a file number for identification. As for file name, you must also specify the path where the file will reside.

For example

Open "c:\My Documents\sample.txt" For Output As #1

will create a text file by the name of sample.txt in the My Document folder. The accompany file number is 1. If you wish to create and save the file in A drive, simply change the path, as follows"

Open "A:\sample.txt" For Output As #1

If you wish to create a HTML file , simple change the extension to .html

Open "c:\My Documents\sample.html" For Output As # 2

14.2.1 Sample Program : Creating a text file

Private Sub create_Click()
Dim intMsg As String
Dim StudentName As String

Open "c:\My Documents\sample.txt" For Output As #1
intMsg = MsgBox("File sample.txt opened")
StudentName = InputBox("Enter the student Name")
Print #1, StudentName
intMsg = MsgBox("Writing a" & StudentName & " to sample.txt ")

Close #1

intMsg = MsgBox("File sample.txt closed")
End Sub

* The above program will create a file sample.txt in the My Documents' folder and ready to receive input from users. Any data input by users will be saved in this text file.

14.3 Reading files

To read a file created in section 14.2, you can use the input # statemment. However, we can only read the file according to the format when it was written. You have to open the file according to its file number and the variable that hold the data. We also need to declare the variable using the DIM command.

14.3.1 Sample Program: Reading file

Private Sub Reading_Click()
Dim variable1 As String
Open "c:\My Documents\sample.txt" For Input As #1
Input #1, variable1
Text1.Text = variable1
Close #1

End Sub

* This program will open the sample.txt file and display its contents in the Text1 textbox.

No comments: