The Filesystem Object Component

The Filesystem Object component makes available two objects for manipulating text files from ASP Web pages. The FileSystemObject object opens or creates text files, and the TextStream object reads and writes to the text file once it's opened.

The FileSystemObject Object

The syntax for creating an instance of the FileSystemObject object is

 <OBJECT RUNAT=server PROGID=Scripting.FileSystemObject      id=objFileSys> </OBJECT> 

This statement instantiates a FileSystemObject object, and it adds a reference to the new object in the objFileSys variable. After the object is created, you can use it to access files. The FileSystemObject object has no properties. Its sole purpose is to create or open text files.

The FileSystemObject object has two methods, one for creating files and one for opening text files. The CreateTextFile method takes the filename you specify and creates the file for you. It returns a TextStream object that you can use to manipulate the file after it's been created. The syntax, explained further in Table 17-3, is

 Set objTextStream = objFileSys.CreateTextFile(FileName,      [Overwrite], [Unicode]) 

Table 17-3. Arguments in the CreateTextFile method of the FileSystemObject object.

Argument Description
objTextStream The variable that contains the TextStream object created by this function.
objFileSys A variable referencing an existing FileSystemObject object.
FileName A string that contains the path to a file. This can be the fully qualified path, including the drive letter and directory, or just the filename. If it's just the filename, the file is created in the root directory of the site.
Overwrite This Boolean value can be set to False to keep the FileSystemObject object from deleting an existing file when you create a new file. This parameter is optional; if you don't specify a value, it defaults to True, and an existing file with the same name is deleted.
Unicode Set this argument to True to write in Unicode format. This is an optional argument, and it defaults to False if omitted.

The OpenTextFile method takes the filename you specify and opens the file. It has arguments that specify in which mode to open the file and what to do if the file is not there. Like CreateTextFile, OpenTextFile returns a TextStream object that you can use to manipulate the file once it's open. The following syntax is explained further in Table 17-4.

 Set objTextStream = objFileSys.OpenTextFile(FileName, [IOMode],      [Create], [Format]) 

Table 17-4. Arguments in the OpenTextFile method of the FileSystemObject object.

Argument Description
FileName This required variable is the path and filename of the file you're trying to open. If you don't include the full path, the FileSystemObject object looks in the root directory.
IOMode This optional constant is either ForReading or ForAppending, indicating that the file is open for either reading or appending.
Create This optional Boolean argument specifies what happens if the file you're trying to open doesn't exist. When set to True, it creates an empty file if the file is not found. When set to False, it generates an error if the file is not found. The default is False if you omit this argument. If you set it to True, you can avoid having to open the file, check for an error, and create the file if the open operation failed.
Format This optional value is one of three Tristate values (TristateTrue for Unicode, TristateFalse for ASCII, and TristateUseDefault for the system default) used to indicate the format of the opened file. If this value is omitted, the file is opened as ASCII.

The TextStream Object

After you open or create the text file, you have a TextStream object. This object represents the file on disk. It has a cursor that, like the cursor in your word processor, indicates where the next typed characters will appear. The TextStream cursor also indicates where characters that you write to the stream will go, and where characters that you read will come from.

You cannot create a TextStream object using the Server.CreateObject method. The only way to get a TextStream object is to open an existing text file or create a new one using the FileSystemObject object as discussed earlier. Table 17-5 lists the properties of the TextStream object, while Table 17-6 lists its methods.

Table 17-5. Properties of the TextStream object.

Property Description
AtEndOfLine A read-only Boolean value. It is True if the cursor is at the end of the current line, False if otherwise.
AtEndOfStream A read-only Boolean value. It is True if the cursor is at the end of the stream, False if otherwise.
Column A read-only integer that indicates the number of characters from the beginning of the line to where the cursor is located.
Line A read-only integer value that indicates the line number in the file where the cursor is located.

Table 17-6. Methods of the TextStream object.

Method Description
Close Closes the stream and its text file.
Read(NumCharacters) Reads the number of characters from the text file starting at the current cursor position. NumCharacters is an integer value. The characters are returned in a string.
ReadAll Reads the entire stream into a string.
ReadLine Reads an entire line into a string.
OSkip(NumCharacters) Moves the cursor a number of characters in the stream.
SkipLines(NumLines) Moves the cursor a number of lines in the stream.
Write(Text) Writes a string to the stream.
WriteLine([Text]) Writes a text string to the stream and appends an end-of-line character to it. This string is optional.
WriteBlankLines(NumLines) Writes a number of blank lines to the stream.

Implementing a Simple Text-Based Data File

You can do many different things with a FileSystemObject object and a TextStream object. To illustrate some of these uses, we'll look at a sample application that uses a text file to record the names and addresses of people who leave that information at your Web site. The code for this sample is located in the Components Web project on the companion CD-ROM.

You want to store everyone's name and address in the same text file. This text file will be opened for write access. Since a file can be opened for write access by only one application at a time, you have to ensure that you try to open the file only once for write access. One way to do this is to execute the Application object's Lock method before you try to write to the file. If the application is already locked when you try to lock it, your session waits until the application is unlocked before proceeding. The downside of using Application.Lock is that you might tie up the Application object for a long time while the operation is pending. Another way to control opening the file only once is to store a reference to the open file in the Application object. If the reference to the file shows that the file is open, don't try to open it; if the reference shows it's not open, you can open it.

Next you build a sample page that lets you obtain a user's name and address, and then you save that information to a text file. The first thing you need is the data to write to the file. A simple HTML form does the trick. The sample HTML form, named FileSystemObject.htm and shown in Figure 17-7, has seven text boxes—two for the user's first and last name and five for the address fields. It calls an ASP file named FileSystemObjectHandler.asp that does the actual work of writing the file.

Figure 17-7. The source code for FileSystemObject.htm captures user input and passes it to FileSystemObjectHandler.asp to create a text file.

 <%@ Language=VBScript %> <HTML> <HEAD> <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0"> </HEAD> <BODY> <H2>FileSystemObject Sample</H2> <HR> <FORM METHOD="POST" ACTION="FileSystemObjectHandler.asp"> <TABLE border=0 cellPadding=1 cellSpacing=1 width=50%>          <TR>         <TD>First Name</TD>         <TD>             <INPUT id=firstname name=firstname></TD></TR>     <TR>         <TD>Last Name</TD>         <TD>             <INPUT id=lastname name=lastname></TD></TR>     <TR>         <TD>Address</TD>         <TD>             <INPUT id=address1 name=address1></TD></TR>     <TR>         <TD>Address</TD>         <TD>             <INPUT id=address2 name=address2></TD></TR>     <TR>         <TD>City</TD>         <TD>             <INPUT id=city name=city></TD></TR>     <TR>         <TD>State</TD>         <TD>             <INPUT id=state name=state></TD></TR>     <TR>         <TD>Zip</TD>         <TD>             <INPUT id=zip name=zip></TD></TR></TABLE> <P><INPUT id=submit name=submit type=submit value=submit></P> </FORM> </BODY> </HTML> 

The FileSystemObjectHandler.asp file creates the text stream and writes the data to the file, as shown in Figure 17-8 below:

Figure 17-8. Source code for the FileSystemObjectHandler.asp file.

 <%@ Language=VBScript %> <HTML> <HEAD> <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0"> </HEAD> <BODY> <% On Error Resume Next ' Lock the application so only one update is allowed at a time Application.Lock %> <OBJECT RUNAT="server" PROGID="Scripting.FileSystemObject"      id="objFileSys"> </OBJECT> <% ' Define the filename and path fname = Server.MapPath("\components\names.txt") ' Create a text stream object and open the file Set MyFile = objFileSys.OpenTextFile(fname, 8) If Err.number <> 0 Then     Set MyFile = objFileSys.CreateTextFile(fname)     Err.Clear End If   ' Prepare the output string OutString = Request.Form("firstname") & "|" & _     Request.Form("lastname") & "|" & _     Request.Form("address1") & "|" & _     Request.Form("address2") & "|" & _     Request.Form("city") & "|" & Request.Form("state") & "|" & _     Request.Form("zip")     ' Write the string to the text file MyFile.WriteLine(OutString) ' Close the file MyFile.Close ' Display a success or failure message If Err.number = 0 Then     Response.Write "<H2>FileSystem Object Sample</H2><HR>"     Response.Write "<P>Data written successfully to " + fname     Response.Write "<P><A HREF=" + fname + ">View the file.</A>" Else     Response.Write "<H2>FileSystem Object Sample</H2><HR>"     Response.Write "<P>An error occurred while writing the " + _         "data to " + fname End If ' Unlock the application Application.UnLock %> </BODY> </HTML> 

You have to do a couple of things before you create the main logic portion of the file. The first line in this script is On Error Resume Next. This means that if the script has an error, the script ignores it and continues executing on the next line. You must have this error trapping in place when you try to open the file. If the file is not there and any script statement has a problem, you get a scripting error. Rather than ending the script, you should continue and try to create a new file. You must expect that the file might not exist and be prepared to handle this possibility. One way to handle the problem of a file not found is to set the Create argument of the OpenTextFile method to True. When set to True, the argument creates an empty file if the file is not found. (See Table 17-4 for more details.)

After setting up error trapping, the script tries to lock the Application object. If it is already locked, the script pauses at that line and waits for the Application object to unlock until the time-out period expires. In this example, you needn't worry about this, but in a larger-scale production environment it might be an issue.

To open a file, you first create a FileSystemObject object by dragging the object onto your ASP Web page from the Toolbox. You also need a filename for the text file you'll write to. The MapPath method of the Server object translates the text file's virtual path—the path within your Web site—to a fully qualified path on a device on your Web server. MapPath returns that path, which is stored in the fname variable.

Next, try to open the file with the OpenTextFile method of the FileSystemObject object. If you can open the file, a TextStream object is created and is assigned to the variable objTextStream. If you cannot open the file, an error is generated. Because of the On Error Resume Next statement, the script continues to run. The next line checks to see if the value of the error object, Err, is not 0. If no error occurred, the value is 0. If the value is anything other than 0, there was a problem opening the file, so try using the CreateTextFile method instead. In a production system, you can determine the exact error by checking the value of the Err object's Number property, but in this example assume that the problem results from a file not being found.

You should now have a TextStream object, whether you had to create a file or open an existing one. Next you use the Request object to get the name and address information that the user typed into the system. The strings are combined with the pipe character between them. This is the string you write to the text file using the WriteLine method. After writing the data, all you have to do is close the text file.

To provide the user with some constructive feedback, check the Err object again. If an error occurred while writing the data, use the Description property of the Err object to relay the error to the user. Otherwise, just thank the user for the input. Either way, you will unlock the Application object before the script ends. You must leave the Application object unlocked or other sessions will get stuck when they try to write data.



Programming Microsoft Visual InterDev 6. 0
Programming Microsoft Visual InterDev 6.0
ISBN: 1572318147
EAN: 2147483647
Year: 2005
Pages: 143

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net