Seems to know why the website counter does not display/(the magic of FSO in ASP)

Source: Internet
Author: User

Source: http://www.15seconds.com/Issue/000816.htm

In ASP, FSO indicates a file system object, that is, a file system object.

The computer file system we want to manipulate is located on the web server. So confirm that 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 access or network drive
FileSystemObject object: File System Object for accessing the computer's File System
Folder object: all attributes of a folder object for access
Textstream object: Text Stream object for accessing File Content

You can use the above objects to do anything on the computer, including destructive activities;-(so please be careful when using FSO. In the web environment, storing information is very important, such as user information, log files, and so on. FSO provides a powerful and simple way to efficiently store 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 all the 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 file system (view the Visual Basic documentation 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, it is not limited to be applied in ASP.

Here is a brief list of FSO methods:

FSO Method
Copyfile: copy one or more files to the new path.
Createtextfile: Creates a file and returns a textstream object.
Deletefile: delete an object
Opentextfile open the file and return the textstream object for reading or appending

For more information about FSO methods and attributes, see Microsoft msdn. Here are several examples.

Suppose 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

'Close and clean 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 file content, such as writing, reading, and skipping a row. The VB constant vbcrlf generates a line break.

The value true is defined in the Command Parameter of opentextfile, which tells the system to create a file if the file does not exist. If the file 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 a file, just like a simple database. Assume that a user wants to know all the visitors
Separated from the information, because there is no structured column like a database.

We know that in the created file, row 1st is the user name, row 2nd is their home page, and row 3rd is their email address. Subsequent Registration
Users store their information according to this structure, so every 3 rows contains a user's registration information. With this knowledge, you can compile the following code to display
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 a file has been correctly created and written, the above small loop will properly list the information of everyone in the database. Readline method read 1
Line content until a line break is encountered, the subsequent Readline call will read the next line. Atendofstream is the property of the textstream object. It tells us when
The end of the file.

Assume that, for some reason, the file is not correctly formed. If a user only has two lines of information instead of three lines, some errors will occur. We
Here, the next three lines of information in the file are retrieved cyclically. 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 processing code to prevent unnecessary rows or unnecessary row information from being inserted in the file.

I discussed the basic knowledge above and then talked about permission licensing issues. FSO is run with the user account permission to create it, in other words, if someone is from the Internet
To access your page, then this Internet account will create FSO. If you log on to the 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 requires some permissions to complete
Execute the function.

Internet account (iuser_machinename, machinename is the name of the server) generally only has read permission, which means that users cannot write
Statement file. However, there are several options to bypass this issue.

First, it is also very difficult to ask the user to log on to the server before entering the message book. However, the main point of the message book is to collect information from anonymous users, such
If users are required 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 file. 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 the content on the server. This is a serious taboo. So you must confirm that
The hidden location stores the information of these writable directories and tries to set these directories out of the web directory structure (for example, in windows, This Is
Is not in the inetpub directory ).

You may think: Well, now I know how to write files. 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 files under the directory, and then execute the same code for all directories cyclically. Because
To determine the total number of subdirectories, you must execute the search code over and over again until the end of the search. Recursive call is very 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 string is in 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 file, FSO requires the actual file path instead of the web path. For example, C: inetpubwwwroot empindex.html, instead
Www.enfused.com/temp/index.html or/temp/index.html. To convert the latter to the former, use server. mappath
("FILENAME"). filename indicates the web path name.

The above code will be executed in each subdirectory of the folder under the initial directory you specified. Here, the initial directory refers to the web root directory "/". Then
Simply open each file in the directory and check whether it contains the specified string. If the string is found, the link to the file is displayed.

Note: As the number of files and subdirectories increases, the search time will also increase. If you need heavy search work, we recommend that you use other methods.
For example, the Index Server of Microsoft's Index Server.

At this point, you may already have a good understanding of FSO. Let's take further research to solve more complex problems.

First, you may want to rename the file. To track all documents, you will rename them to be unique so that they can be easily located by the system.
No. Unfortunately, FSO does not allow simple file rename operations, so we have to modify it.

<%
'Create the FSO object
Set FSO = server. Createobject ("scripting. FileSystemObject ")
Path = "C: EMP est.txt"
Strdate = Replace (date (),"/","")
Strdir = "C: inetpubwwwrootarticles" & strdate
Strnewfilename = hour (now) & "_" & minute (now )&"_"&
Second (now) & ". html"

'Open the old file
Set file = FSO. opentextfile (path, 1) <-- for reading
Strtext = file. readall
Set file = nothing

'Check for and/or create folder
If not FSO. folderexists (server. mappath (strdir) then
Set F = FSO. createfolder (server. mappath (strdir ))
Else
Set F = FSO. getfolder (server. mappath (strdir ))
End if

'Create and write new file
Set file = FSO. createtextfile (F. Path & "" & strnewfilename)
File. Write (strtext)
Set F = nothing
File. Close
Set file = nothing

'Delete the old file
FSO. deletefile (Path & "& RST (" FILENAME ") & I)
'Clean up
Set FSO = nothing
%>

The lack of FSO capabilities has become an advantage here. We can perform two steps at a time. First, open the file and read the content of the file. Suppose you want to create
A unique folder and a unique file are used to store articles. However, because the folder path changes every day, you must first check whether the folder has been
Yes. If not, create it. This is done in the if not FSO. folderexists code segment. Then, obtain the path and create a new file. New
After the file is created, delete the old file, which is completed by FSO. deletefile.

The two steps are: Rename the file and move it to a more appropriate directory. Note: You can perform more operations on files, such
Edit the content before entering the new file.

FSO does have some weaknesses-for example, it is difficult to process binary files, including Word documents, many graphical files and other files. However, you can still operate these files in other ways-move them, delete them, and so on. What you cannot do is to open or write them.

Another restriction is the file length. When you read and write some content immediately, all information is stored in the memory. The more content, the larger the memory consumption. This slows down every job. Therefore, if you need to operate a very large file, or a large number of small files, consider splitting the file into small blocks and frequently clearing the memory. Integrating applications into COM Object components can greatly increase the program speed.

Similarly, you cannot use FSO to manage permissions and attributes of files and folders. A good way to perform security encryption is to set the aforementioned message book file to read-only, set it to writable when necessary, and then modify it back. This method is often used in CGI and Perl, but unfortunately there is no satisfactory method to implement it with FSO.

What else can FSO be used?

There are many great features in FSO, but many people don't realize it. These features are often discovered only when you feel that it is difficult to do something. At this time, you often have to lament that it would be nice if I knew this method!

The following lists some of the functions that are not commonly used but are cool:

FSO features rarely known
Getspecialfolder method returns the path of the specific Windows Folder: Windows installation directory; Windows System directory; Windows temporary directory FSO. getspecialfolder ([0, 1, or 2])
Gettempname method returns a randomly generated file or directory name, which is used when temporary data needs to be stored.
Getabsolutepathname method returns the absolute path of the folder (similar to server. mappath ).
For example, FSO. getabsolutepathname ("region") returns a result similar to the following: "C: mydocsmyfolder egion"
Getextensionname method returns the extension of the last part of the path.
(For example, FSO. getextensionname ("C: Docs est.txt") will return TXT)
Getbasename and getparentfolder Methods return the parent folder of the last part of the path
(For example, FSO. getparentfolder ("C: docsmydocs") will return 'docs ')
Drives property returns a collection of all available local drives, used to create a resource browser-like user interface.

When using the above functions, it is best to establish the error handling code. If the required parameter does not exist, it will produce troublesome information.

Summary

As we have seen, FSO is very useful. Here we are only introducing the tip of the iceberg. You can use FSO to build powerful applications and simply complete many tasks.

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.