In-depth understanding of the magic functions of FSO in ASP

Source: Internet
Author: User

 

In ASP, FSO indicates File System Object, that is, the document System Object.
The computer document system we are about to manipulate is located on a web server. Therefore, make sure you have the appropriate permissions. Ideally, you can create a web server on your own machine to facilitate testing. If you are running on Windows, try Microsoft's free personal Web Server PWS.
FSO model object
Drive Object: Drive Object for disk or network Drive access
FileSystemObject Object: Document System Object for accessing the computer's Document System
Folder Object: Any attribute of the document Folder for access.
TextStream Object: Text Stream Object for accessing document content
You can use the above objects to do anything on the computer, including destructive activities;-(so be careful when using FSO. In the web environment, storing information is very important, such as user information, log documents, and so on. FSO provides a powerful and simple method with highEfficiencySave data. In this article, we will focus on FileSystemObject and TextStream objects.
FSO is supported by Microsoft and cannot be used for non-Windows systems.
How to Use FSO?
To use FSO to execute any work, you must first create an object. The Code is as follows:

<% Set fso = Server. CreateObject ("Scripting. FileSystemObject ")
%>

In this way, the FSO is created and the variable fso is assigned, and then the familiar object can be used. method syntax to perform operations on the document system (view the Visual Basic document to learn more about object and object wizard programming 〕. Here, we can use fso. method or fso. property, which will be seen in the following example.
The FSO model is located in the script run time DLL file provided by Microsoft. It is scrrun. dll. You can reference this DLL file in any application, such as MS Access and Word. That is to say, not justRestrictionsApply it in ASP.
Here is a brief list of FSO methods:

FSO Method

CopyFile
Copy one or more documents to the new path

CreateTextFile
Creates a document and returns a TextStream object.

DeleteFile
Delete a document

OpenTextFile
Open the document and return the TextStream object for reading or appending

For more information about FSO methods and attributes, see Microsoft MSDN. Here are several examples.
Assume that you want to create a simple message book. You can create a database to store user information. However, if you do not need the powerful functions of the database, using FSO to store information will save you time and money. In addition, some ISPs may restrict database applications on the web.
Suppose you have collected some user information in a form. Here is a simple form HTML code:

<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 code for processing the form in formhandler. asp:

<%
'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, nothing is new. It is nothing more than getting the values of form fields and assigning values to variables. An interesting part is shown below:

Path = "c: emp est.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
'CloseAndClean up
File. close
Set file = nothing
Set fso = nothing

In retrospect, the OpenTextFile method returns a TextStream object, which is another object in the FSO model. TextStream objects reveal methods for operating document content, such as writing, reading, and skipping a row. The VB constant vbcrlf generates a line break.
Define TRUE in the Command Parameter of OpentextFile, which tells the system that if the document does not exist, create it. If the document does not exist and the TRUE parameter is not defined, an error occurs.
Now go to the directory c: empand open test.txt. You can see the following information:

User's name
User's home page
User's email

Of course, these words can be replaced by any input in the form.
Now some user information is saved in the document, just like a simple database. Assume that a user wants to know any visitor, the relevant information should be separated from the registration information, because there is no structured column like the database.
We know that in the document we created, the first line is the user name, the second line is their home page, and the second line is their email address. Subsequent registered users store their information according to this structure, so each row contains a user registration information. With this knowledge, you can write the following code to display information:

<%
'Create the fso object
Set fso = Server. Createobject ("Scripting. FileSystemObject ")
Path = "c: emp est.txt"
'Open the file
Set file = fso. opentextfile (path, 1) <--
Reading

Next, analyze each row and format the data:

Do until file. AtEndOfStream
Response. write ("Name:" & file. ReadLine &"")
Response. write ("Home Page:" & file. ReadLine &"")
Response. write ("Email:" & file. ReadLine & "<p> ")
Loop
'Close and clean up
File. close
Set file = nothing
Set fso = nothing
%>

Only a simple output is provided here, but you can include the table or DHTML form information as needed.
If the document has been correctly created and written, the above small loop will properly list the information of every person in the database. The ReadLine method reads one line of content until it encounters a line break. The subsequent ReadLine call reads the next line. AtEndOfStream is the attribute of the TextStream object. It tells us when the end of the document will be reached.
Assume that, for some reason, we have not correctly formed the document. If a user has only two lines of information instead of three lines, some errors will occur. Here, we cyclically retrieve the next three lines of information in the document. If there are no more than three lines of information, the following error message will appear:

Server object error 'asp 0177: 800a003e'

Therefore, you must add some error handling code to prevent unnecessary lines or unnecessary line information from being inserted in the document.
I discussed the basic knowledge above and then talked about permission licensing issues. FSO is run with the permission to create a user account. In other words, if someone visits your page from the Internet, this internet account will create FSO. If you log on to your computer as administrator and log on to the page, the administrator account creates FSO. This is very important because a certain account has certain permissions and FSO needs some permissions to execute functions completely.
Internet account (IUSER_MachineName, MachineName is the name of the server) generally only has read permission, which means that users cannot write to the guestbook document. However, there are several options to bypass this issue.
First, it is very difficult to log on to the server before entering the message book. However, the main point in the message book is to collect information from anonymous users. If users need to log on, they must know who they are. Therefore, skip this selection and look at the next one.
The first method is to create a directory or document. The IUSER_MachineName user has the write permission for this. This may expose some potential security vulnerabilities, because anyone who knows the correct directory and has certain web skills can fill in the content on the server. This is a serious taboo. Therefore, you must make sure that the information about these writable directories is saved in a hidden place and that these directories are configured out of the web directory structure as much as possible (for example, in Windows, this is a directory not in the inetpub directory ).
You may think: Well, now I know how to write the document. But can we do more? Next, let's try to create a search function for the web site.
The key to building a search engine is recursion. Mainly, write a piece of code to search for the documents under the directory, and then execute the same code on any directory in a loop. Because you cannot determine the total number of subdirectories, you must execute the search code over and over again until the end. Recursive call is good!
Create a search page. Assume that an HTML form has been created and the user enters a search string.

Dim objFolder
Dim strSearchText
Dim objFSO
StrSearchText = Request. Form ("SearchText") <-- The search string
'Create the FSO and Folder objects
Set fso = Server. CreateObject ("Scripting. FileSystemObject ")
Set objFolder = objFSO. GetFolder (Server. MapPath ("/"))
Search objFolder

The above code initializes the variable. The Search function executes the Search function, which is described as follows:

Function Search (objFolder)
Dim objSubFolder
'Loop through every file in the current
Folder
For Each objFile in objFolder. Files
Set objTextStream = objFSO. OpenTextFile (objFile. Path, 1) <-- For Reading
'Read the file' s contents into
Variable
StrFileContents = objTextStream. ReadAll
'If the search stringIsIn the file, then
Write a link
'To the file
If InStr (1, strFileContents, strSearchText, 1) then
Response. Write "<a href =" "/" & objFile. Name &_
">" & ObjFile. Name & "</A> <BR>"
BolFileFound = True
End If
ObjTextStream. Close
Next
'Here's the recursion part-for each
'Subfolder in this directory, run the Search function again
For Each objSubFolder in objFolder. SubFolders
Search objSubFolder
Next
End Function

To open a document, FSO requires the actual document path instead of the web path. For example, c: inetpubwwwroot empindex.html instead of www.enfused.com/temp/index.html or/temp/index.html. To convert the latter to the former, use Server. MapPath ("filename") and filename to indicate the web path name.
The above code will be executed in each subdirectory of the document folder under the initial directory you specified. Here, the initial directory refers to the web root directory "/". Then, you can simply open each document in the directory and check whether it contains the specified string. If the string is found, the link to the document will be displayed.
Note that as the number of documents and subdirectories increases, the search time will also increase. If you need heavy search work, we recommend that you use other methods, such as the Index Server of the Indexing Server of Microsoft.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.