Writing Files
August 14, 2000
Suppose you wanted to create a simple guestbook. You could set up a
database and store users' information there.
However, if you don't
need the power of a database application, you can save yourself some
money and overhead, and use the FSO to store your information. Not to
mention the fact that your ISP may limit your choice of database
options.
Let's assume you'll collect some user information in a form.
(Check out
WDVL's primer on forms.) Here's the HTML for a simple form:
<html>
<body>
<form action="formhandler.asp" method="post">
<input type="text" size="10" name="username">
<input type="text" size="10" name="homepage">
<input type="text" size="10" name="Email">
</form>
</body>
</html>
Let's look at the script in formhandler.asp that will handle
the form:
<%
' Get form info
strName = Request.Form("username")
strHomePage = Request.Form("homepage")
strEmail = Request.Form("Email")
' create the fso object
Set fso = Server.CreateObject("Scripting.FileSystemObject")
So far, this should be nothing new. We take the form variables and
assign them to variables for easier use later on. Now comes the fun
part - writing the file:
path = "c:\temp\test.txt"
ForReading = 1, ForWriting = 2, ForAppending = 3
' open the file
set file = fso.opentextfile(path, ForAppending, TRUE)
' write the info to the file
file.write(strName) & vbcrlf
file.write(strHomePage) & vbcrlf
file.write(strEmail) & vbcrlf
' close and clean up
file.close
set file = nothing
set fso = nothing
As you recall, the OpenTextFile method returns a TextStream object,
which is another object of the FSO model. The TextStream object
exposes
methods
to manipulate a file's content, such as
Write, ReadLine, and SkipLine. The VB constant vbcrlf generates
a line break.
|
NOTE:
We specify TRUE in the argument list of OpentextFile to
tell the system to create the file if it doesn't already
exist. If the file does not exist, and you do not specify
TRUE, you will generate an ugly error.
|
Now navigate to c:\temp and open test.txt. You should see the following
information:
User's name
User's home page
User's email
Of course those words will be replaced by whatever the user entered
in the form. Now anyone can come along and fill out your guestbook
and their information will be stored in this file.
How do I use the FSO?
The wonders of the File System Object
Reading Files
|