In ASP, FSO means File System Object, which is a file system object.
The computer file system we are going to manipulate refers to being located on the web server. So, make sure you have the right permissions for this. Ideally, you can set up a web server on your own machine so that you can easily perform testing. If running on Windows, try Microsoft's free personal web server PWS.
FSO Model Objects
Drive Object: Drive objects for accessing disks or network drives
FileSystemObject Object: File system objects for accessing the computer's file system
Folder Object: Folder object for accessing all properties of a folder
TextStream Object: Text stream object for accessing file content
You can use the above object to do anything on your computer, including sabotage activities;-( So, be careful with FSO. In a web environment, it is very important to store information, such as user information, log files, etc. FSO Provides a powerful and simple way to save data efficiently. In this article, we focus on FileSystemObject and TextStream objects.
FSO is powered by Microsoft and ASP is probably no longer available for non-Windows systems.
How to use FSO?
In order to use FSO to perform all work, first create an object, the code is like this:
| < %Set fso = Server.CreateObject(Scripting.FileSystemObject) % > |
This creates FSO and assigns the variable fso. Then you can use the familiar object.method syntax to perform the operation of the file system [see Visual Basic documentation for more knowledge 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 a script runtime DLL file provided by Microsoft, which is scrrun.dll. You can reference this DLL file in any application, such as MS Access, Word. That is, it is not just limited to applying it in ASP.
Here is a brief list of FSO methods:
| FSO method | |
| CopyFile | Copy one or more files to a new path |
| CreateTextFile | Create a file and return a TextStream object |
| DeleteFile | Delete a file |
| OpenTextFile | Open the file and return the TextStream object for reading or appending |
If you want to know the complete FSO methods and properties, please refer to Microsoft MSDN. Let’s see a few examples below.
Suppose you want to create a simple guestbook where you can create a database where you store user information. However, using FSO to store information will save you time and money if the power of the database is not required. And, 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 take a look at the code that processes forms 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 new is nothing more than getting the value of the form field and assigning values to variables. An interesting part appears below - Write a file:
| 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 |
Recall that the OpenTextFile method returns a TextStream object, which is another object in the FSO model. The TextStream object reveals ways to manipulate file content, such as writing, reading, and skipping a line. The VB constant vbcrlf produces a newline character.
TRUE is defined in the command parameter of OpentextFile, which tells the system that if the file does not exist, create it. If the file does not exist and the TRUE parameter is not defined, an error occurs.
Now go to the directory c:emp, open test.txt, and you can see the following information:
| User's name User's home page User's email |
Of course, these words can be replaced by anything entered into the form.
Now some user information is saved in a file, like a simple database. Suppose there is a user who wants to know all visitors and separate the relevant parts from the registered information because there is no structured column like a database.
We know that in the file created, line 1 is the username, line 2 is their homepage, and line 3 is their email address. The registered users will also store their information in this structure, so every 3 lines will contain one user's registration information. Knowing this, you can write the following code to display the 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) < -- For 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 %> |
This is just a very simple output, but you can include table or DHTML form information according to the situation.
If the file has been correctly created and written, the small loop above will properly list the information of everyone in the database. The ReadLine method reads 1 line of content until a newline is encountered, and the subsequent ReadLine call will read the next line. AtEndOfStream is a property of a TextStream object that tells us when we encounter the tail of a file.
Assume that for some reason we are not forming the file correctly, if a user has only 2 lines of information instead of 3 lines, then some errors will occur. Our loop here retrieves the next 3 lines of information in the file. If there is no more than 3 lines of information, the following error message will appear:
| Server object error 'ASP 0177 : 800a003e' |
Therefore, be sure to add some error handling code to prevent unnecessary lines from being inserted into the file or the necessary line information is missing.
The basic knowledge is discussed above, and then the issue of permissions is discussed. FSO runs with the user account that creates it, in other words, if someone accesses your page from the Internet, then this internet account creates FSO. If you log in to the computer as administrator and log in to the page, the administrator account creates the FSO. This is very important because a certain account has certain permissions, and FSO requires some permissions to fully execute functions.
Internet accounts (IUSER_MachineName, MachineName is the name of the server) generally only have read permissions, which means that the user will not be able to write to the guestbook file. However, there are several options to bypass this problem.
First of all, it is also very difficult, requiring users to log in to the server before filling in the guestbook. However, the key point of the guestbook is to collect information from anonymous users, and if the user is asked to log in, you must know who they are. So, skip this option and see the next one.
The second method is to create a directory or file, and the IUSER_MachineName user has write permissions. Doing so may open up some potential security vulnerabilities, because anyone who knows the correct directory and has some web skills can fill in content on the server. This is a serious taboo. So you must confirm that the information of these writable directories is saved in the hidden place and set these directories outside the web directory structure as much as possible (for example, under Windows, this is a directory that is not in the inetpub directory).
You might think: OK, now I know how to write to the file. But can we do more? 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 in the directory, and then execute the same code on all directories loops. Since it is not possible to determine how many subdirectories are in total, the search code must be executed over and over until it is finished. Recursive calls are very good!
Let’s create a search page. Suppose an HTML form has been created, where 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 simply initializes the variables, and 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 a 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 |
In order to be able to open a file, FSO requires the actual file path, not the web path. For example, it is c:inetpubwwwroot empiindex.html, not www.enfused.com/temp/index.html or /temp/index.html. In order to convert the latter to the former, use Server.MapPath(filename), filename to represent the web path name.
The above code will be executed in each subdirectory of the folder under the initial directory you specify, where the initial directory refers to the web root directory/. Then simply open each file in the directory to see if it contains the specified string. If the string is found, the link to that file will be displayed.
Note that as the number of files and subdirectories increases, the time it takes for searches will increase. If you need heavy search work, you are advised to take other methods, such as Microsoft's index server Index Server.
At this point, you may have a good understanding of FSO. Let's take a deeper look at it to solve more complex problems.
First, you may want to rename the file. To keep track of all documents, you will want to rename them to be unique so that they can be easily distinguished by the system. Unfortunately, FSO does not allow simple file name change 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, and we can perform 2 steps at a time. First, open the file and read the contents of the file. Suppose here you want to create a unique folder and a unique file to store the article. However, because the path to the folder will change every day, it must be first checked whether the folder already exists and if it does not exist, create it. This is done in the if not fso.folderexists snippet. Then, take that path and create a new file. After the new file is created, delete the old file, which is done through fso.DeleteFile.
These 2 steps are: rename the file and then move it to a more suitable directory. Note that you can also do more operations on files here, such as editing content before writing to a new file.
FSO does have some weaknesses - for example, it is difficult to handle binary files, which include Word documents, files in many graphic formats, and some other files. However, you can still manipulate these files in other ways - move them, delete them, etc. All you can't do is open or write them.
Another limitation is the problem of file length. When some content is read and written immediately, all the information is stored in memory - the more content, the more memory it consumes. This will slow down every job. Therefore, if you need to operate very large files, or large numbers of small files, consider dividing the files into small pieces and clearing the memory frequently. Incorporating applications into COM object components can also greatly improve the speed of the program.
Similarly, you cannot use FSO to manage permissions and file and folder properties. A good way to perform secure encryption is to set the aforementioned guest book file to read-only, and then set it to writable if needed, and then Modify it back. This method is often used in CGI and Perl, but unfortunately, there is no satisfactory way to implement it with FSO.
What else can I do with FSO?
There are many great features in FSO, but many people don't realize it. These functions are often discovered after you feel it is difficult to do something. At this time, you often sigh: If only I had known this method!
Here are some of these incommon but very cool features:
FSO features that are rarely understood
GetSpecialFolder Method Returns the path to a 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 to require GetAbsolutePathName Method Returns the absolute path to the folder (similar to Server.MapPath) when storing temporary data.
For example, FSO.GetAbsolutePathName(region) will return a result similar to the following: c:mydocsmyfolder oxide
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 Returns 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 locally available drives for establishing a resource browser-like user interface.
When using the above functions, it is best to create a code for error handling. Because if the required parameters do not exist, troublesome information will be generated.
Summarize
As we have seen, FSO is very useful, and what we are introducing here is just the tip of the iceberg. You can use FSO to build powerful applications and simply complete many tasks.