Getting the list of files inside a directory by using FileSystemObject in ASP

By using FileSystemObject (FSO)we can list out all the files of a directory. Here we will be using server MapPath to map the virtual path to real path as used by file system object. After initiating the object we can instantiate the folder object. We will be using this folder object Files property to get all the files present within the folder.

FileSystmObject

We can check whether file of folder exists at a location by using file system object ( FileSystemObject). This is often required to check the existence of a file or directory before using, otherwise system will generate an error message which is not good to display to the visitors. So before using any file or folder we can check the status of them.

FileSystemObject or fso uses physical path of the file or folder to check the existence so before using this we have to convert the virtual path to physical path for our folders or files by using server.mappath object.

We will use one variable to hold the instance of the FileSystemObject and using this we will check the existence of the file or folder.
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Next we will use the If Then Else statement to check the condition of the file or folder.
If objFSO.FolderExists(Server.MapPath("db")) Then
Response.Write "Folder Exists"
else 
Response.Write "Folder does not exit"
End if
Here "db" is the name of the folder we are checking the existence. We have used the command Server.MapPath to change the virtual path to physical path of the folder db.

We can print the command based the response of the object ( True or False ) and display the message accordingly.

Same way we can use objFSO.FileExists to check the existence of a file at any location.
Dim  FSOobj,FilePath
FilePath=Server.MapPath("text.txt") ' located in the same director 
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
if FSOobj.fileExists(FilePath) Then
Response.Write "File Exists "
Else
Response.Write "File does not exist"
End if
Set FSOobj = Nothing
In our example we have used the folder name my_folder which is inside the directory name t so the path of the folder is
https://mysite.com/t/my_folder/

Here is the code.
Dim objFSO, objFile, objFolder

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Server.MapPath("/t/my_folder"))

For Each objFile in objFolder.Files
Response.Write objFile.Name & "<br>"
Next
Set objFolder = Nothing
Set objFSO = Nothing

Displaying last updated date along with the file name

We can add the last modified date of the file by adding the DateLastModified property of the File object. This one line we will add inside the For Each Loop.
For Each objFile in objFolder.Files
Response.Write objFile.Name & " : "
Response.Write objFile.DateLastModified & "<br>"
Next
Read more on How DateLastModified is used below

How to get current ASP script running file name without using FileSystem object

We can get the current file name of the asp script without using the FileSystem object. The reason for this is we want to develop a common script which can be used ( or included ) in any file to display various file system properties. The FileSystem object needs the file name as input so we will try to develop this script which can be used as a input to the FileSystem object for further development.

The best example is to develop a script which will display the last modified date of the file. Let us start with how to read the script name in ASP. The code used below will give the file name along with the directory or the path name.
Dim my_array, fname
fname = Request.ServerVariables("SCRIPT_NAME")
The above code will display the file name with full path. For example if the present file is in my_file directory and file name is test.asp then the output will be
/my_file/test.asp
To get the file name out of the above full path string we have to break the string and create an array by using split function with "/" as delimiter. Once the array is created we can get the last element of the array to get the file name. Here we will be using Ubound function to get the size of the array and we will use that to get the last element of the array.

Here is the full code to display the current file name
Dim my_array,  fullname, fname
Response.Write Request.ServerVariables("SCRIPT_NAME") & "<br>"
fullname = Request.ServerVariables("SCRIPT_NAME")
my_array=split(fullname,"/")
fname=my_array(ubound(my_array))
Response.Write fname

Reading data of a file by ASP File system object

While reading the content of the file we can use three different ways to collect the data. One is by specifying number of chars we are interested in collecting or reading.
Response.Write OpenFileobj.Read(3)
The above line will collect 3 characters from the file to read the next 3 again we have to use the same command. As we are not aware of how many characters are present inside the file so we will use a loop to collect all the data in a set of 3 chars. Here we have to check that we have not reached the end of the file. We will get this error message
Error Type:
Microsoft VBScript runtime (0x800A003E)
Input past end of file
If there are two chars left then our last command should collect the two chars and should not try again. To do this we will use command OpenFileobj.AtEndOfStream . This will became true once the file end is reached.
Do While Not OpenFileobj.AtEndOfStream
We can also read line by line by changing the read command to ReadLine. Here is the code to read one line each time.
Response.Write OpenFileobj.ReadLine
Same way we can read all the content of the file by using a single command ReadAll like this
Response.Write OpenFileobj.ReadAll 
This is to be used when the file we are reading is not big as this command uses lot of memory to store all the data.

Here is the code used to read the data from a text file. You can see we have used Server.MapPath to map the path of the file we are going to read.
<%
Dim OpenFileobj, FSOobj,FilePath FilePath=Server.MapPath("text.txt") ' located in the same director Set FSOobj = Server.CreateObject("Scripting.FileSystemObject") if FSOobj.fileExists(FilePath) Then Set OpenFileobj = FSOobj.OpenTextFile(FilePath, 1) Do While Not OpenFileobj.AtEndOfStream Response.Write OpenFileobj.ReadLine & "<br>" Loop OpenFileobj.Close Set OpenFileobj = Nothing Else Response.Write "File does not exist" End if Set FSOobj = Nothing %>

Writing data to text file using FSO

For writing to a file we have to open the file in writing mode. This line within our script ( full code is given at the end of this tutorial ) does that.
Set OpenFileobj = FSOobj.OpenTextFile(FilePath, Writing)
In the above line we have used the constant Writing and its value is declared at the starting as 2. You can write 2 in the place for opening the file in writing mode.
Please note that to open file in writing mode, we should have write permission for the file , otherwise we will get an error message similar to this.
Error Type:
Microsoft VBScript runtime (0x800A0046)
Permission denied
writing.asp, line 28
In the writing mode fresh data is written to the file, so old data is erased every time the file is opened in write mode.
Writing Data into the file
We can use different types to write data to the file. One is file simple write like this
OpenFileobj.Write("my data here")
This will write the string my data here to the file. Next we will write one line of data to the file.
OpenFileobj.WriteLine(" Welcome to Plus2net.com ")
The above line will add one line of text Welcome to Plus2net.com to the file. This text will be added to the previous text string ( my data here ) as a continuous within one line. But know one line break will be added at the end of the second string as we have used WriteLine command. This command will always add one line break after adding the string ( not before ). To see the line breaks open your text file in notepad. Your web browser won't show line breaks as browser understand <br> tag as line breaks.

Now let us learn how to add blank lines. Here is the command.

OpenFileobj.WriteBlankLines(4)
Here we are adding four line breaks. Using this combination we can create the script to write data to a file. Here is the full script.
<%
Const Writing=2
Dim OpenFileobj, FSOobj,FilePath
FilePath=Server.MapPath("text.txt") ' located in the same directory 
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
if FSOobj.fileExists(FilePath) Then 
Set OpenFileobj = FSOobj.OpenTextFile(FilePath, Writing)
OpenFileobj.Write("my data here")
OpenFileobj.WriteLine(" Welcome to Plus2net.com ")
OpenFileobj.Write("Learn ASP- VBScript the programming language ")
OpenFileobj.WriteBlankLines(4)
OpenFileobj.WriteLine("You can develop interactive web pages ")
OpenFileobj.Write("Thank you & Visit again")
OpenFileobj.Close
Set OpenFileobj = Nothing
Else
Response.Write "File does not exist"
End if
Set FSOobj = Nothing
%>

Appending data to file in ASP

In the same ASP ( VBScript) script if the mode is changed to append mode then the data will be written at the end of the file without deleting the old data. So just change the constant value and the mode of the file opening. Here are the changes required.
Const Appending=8
Set OpenFileobj = FSOobj.OpenTextFile(FilePath, Appending)
You can easily locate the above two changes in the script given above on write data section and replace it.

Example

We will develop one form to store the email submitted by the users. Each time one visitor submits an email address it has to be added at the end of the file. Note that this is not a newsletter script and many other features like checking the email address etc are not discussed here. This is to be used only to understand how the file appends system works.

We will display one simple form which submits to itself and if the length of the data submitted is more than 2 char length then by using one if condition we will execute the append script.

Please create a blank file as text.txt in the same directory and execute the script. Here is the full code.
<form method=post action=''>
<input type=text name=email><input type=submit value=Submit>
</form>
<%
Dim email
email = Request("email")
if len(email) > 2 Then 
Const Appending=8
Dim OpenFileobj, FSOobj,FilePath
FilePath=Server.MapPath("text.txt") ' located in the same directory
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
if FSOobj.fileExists(FilePath) Then
Set OpenFileobj = FSOobj.OpenTextFile(FilePath, Appending)
OpenFileobj.WriteLine(email)
OpenFileobj.Close
Set OpenFileobj = Nothing
Else
Response.Write "File does not exist"
End if
Set FSOobj = Nothing
End if
%>

File Size by using FSO

The file size is in bytes. We will check first if file exist or not and then we will check the size of the file. This file exists in the root of this script. Here is the code.
<%
Dim  FSOobj,FilePath,details
FilePath=Server.MapPath("text.txt") ' located in the same director 
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
if FSOobj.fileExists(FilePath) Then 
Set details=FSOobj.GetFile(Server.MapPath("text.txt"))
Response.Write  " File Size =  " & details.Size & " Bytes "
Else
Response.Write "File does not exist"
End if 
Set FSOobj = Nothing
%>

File Path by using FSO

Something in a shared hosting environment we need to know the address or absolute path from the server root we need to know. By using FSO we can get it. Here is the code
<%
Dim  FSOobj,FilePath,details
FilePath=Server.MapPath("text.txt") ' located in the same director 
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
Set details=FSOobj.GetFile(Server.MapPath("text.txt"))
Response.Write  " File Path =  " & details.path 
Set FSOobj = Nothing
%>

Relative and Virtual file Including in ASP

Efficient coding requires reusable common code which gets linked to more than one file. In ASP we will be using file include to add codes inside one external file to our required file. There can be many reasons to use file include inside our ASP scripts

Menu or links area

Let us say we have a site with more pages ( say one hundred ) and we have added one more page to this site. The link of this section or page has to be connected to all hundred pages so we have to edit all the required pages were the link to this new page is to be added. A better solution is to use one menu.asp file and include the file inside every asp file like this
<!---#include file="menu.asp" --->
We only have to add our new page link inside the menu.asp file and it will appear all the pages which have included this menu.asp file.

Here the menu.asp file is located in the same directory as the main files calling this include file. If this is inside another directory say my_dir then it has to be included like this.
<!---#include file="my_dir/menu.asp" --->
Another requirement is to keep the database connecting string. Say your host has given you a set of login id , password and database detail ( known as connecting string ). We will be using database in many files so using the connecting string to connect to database. So rather than keeping this connecting string in each and every file we will keep in one connection.asp file and include this inside all required files. Now this will help us a great when we shift our site to a new host. As the new host give a new connection string we need to change this connection.asp file only. Another way it helps we are maintaining a copy of the site in our local computer with its own connecting string.

Including Virtual

We can include a file located from the root of the virtual directory. Say our connection string is kept at root of our virtual directory. Now from any level the same file can be included like this .
<!-- #include virtual = "/connection.asp" -->
Another point we have to keep in mind while keeping sensitive data like connecting string is file extension. If we keep the file name as connection.inc and any one open the file in browser then all the code with database login details will be exposed. So we have to keep these data inside a file with .asp extension.

Include files are always included first before all other codes of main file gets executed. So we can't keep any condition like if else to dynamically include any file.

How to get last updated & created date and time of an ASP file

We will try to develop a code for showing the last modified date and the created date of the file and display to visitors. This code has to work on it own without any input or changed settings.

To make this code universal we will not use name of the file as input to this FileSystemObject , it its place we will use code to get the current file name and then use that as input to FileSystemObject. This way we can make it independent of file name setting and the same code can be used inside any asp file without any changes.

Here is the code to get the current file name and to create FileSystemObject.
Dim objFSO, objFile, fname, fullname, my_array
fullname = Request.ServerVariables("SCRIPT_NAME")
my_array=split(fullname,"/")
fname=my_array(ubound(my_array))

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(Server.MapPath(fname))
To these lines we will add the file name and DateCreated and DateLastModified to get the full code to display the modified time.
Response.Write "Created  date of file "& objFile.Name & " = " & objFile.DateCreated
Response.Write "
Last Modified date of file "& objFile.Name & " = " & objFile.DateLastModified
Note that the above code can be used in any asp file without any modification to get the last updating and creating date and time of the file.

Page hit counter by reading and writing data to file

By using our reading and writing data to file techniques we learn so far and by using FSO, we can develop a counter script. This script will store the count value in a text file. Each time the file is opened the script will read the value from the text file and then store it again by increasing it by one. We can call this as page hit counter, which will tell us how many times a page is opened.

This script uses concepts of reading data from file and writing data to file. So before developing this script it is advisable to understand these scripts by reading the respective tutorials.

The page hit counter script we will divide into two parts. First part will read the previously stored count value. Second part will add 1 to the counter value and write the new value to the text file. So while using this script for first time create one simple text file count.txt and store a value 0 inside it.

In the first part after reading the value we have stored the value of the counter in a variable count. Then we will close the file ( in reading mode ) and open the file again in writing mode. Here is the complete script to develop a simple page hit counter.
<%
Const Reading=1
Const Writing=2
Dim OpenFileobj, FSOobj,FilePath,count
FilePath=Server.MapPath("count.txt")
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
if FSOobj.fileExists(FilePath) Then 
Set OpenFileobj = FSOobj.OpenTextFile(FilePath, Reading)
count = OpenFileobj.ReadLine
  Response.Write count 
OpenFileobj.Close
Set OpenFileobj = Nothing

'Reading of files is over , now let us start writing new count value to file
Set OpenFileobj = FSOobj.OpenTextFile(FilePath, Writing) count=count+1 OpenFileobj.Write(count) OpenFileobj.Close Set OpenFileobj = Nothing Else Response.Write "File does not exist" End if Set FSOobj = Nothing %>

Drive Name by using FSO

We can get the name of the drive in which the file reside by using drive property.
<%
Dim  FSOobj,FilePath,details
FilePath=Server.MapPath("text.txt") ' located in the same director 
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
Set details=FSOobj.GetFile(Server.MapPath("text.txt"))
Response.Write  " Drive Name =  " & details.Drive 
Set FSOobj = Nothing
%>

Deleting File by using DeleteFile

We can delete a file by using File system object or FSO in Active Server Page ( ASP). We can delete the file by using DeleteFile object. We will use the same FSO and server Map Path to define the path of the file to be deleted.

Before applying the delete command we will be checking if the file is there or not by using file exist command.
Dim OpenFileobj, FSOobj,FilePath
FilePath=Server.MapPath("images/myfile.asp")
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
if FSOobj.fileExists(FilePath) Then 

Response.Write "file Exist"
Response.Write "<br>Deleted file  "&FSOobj.DeleteFile(FilePath)

Else
Response.Write "File does not exist"
End if 
Set FSOobj = Nothing
We can check the file extension and use one if condition to delete only a particular type of file.

Getting the file extension and main part name

We can collect the main file name and the extension or type of the file name by using file system object in ASP. We will use the object GetExtensionName to collect the extension or file type name. Same way we can use GetFileName to get the main part of the file name. To know the base directory of the file we can use GetBaseName object.

We will use the server map path to declare the path of the file and then use the FileExists to find out the existence of the file.


Here is the complete code.
Dim OpenFileobj, FSOobj,FilePath
FilePath=Server.MapPath("images/all11.css")
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
if FSOobj.fileExists(FilePath) Then

Response.Write "file Exist"
Response.Write "<br>File Extension Name: "&FSOobj.GetExtensionName(FilePath)
Response.Write "<br>File Name: "&FSOobj.GetFileName(FilePath)
Response.Write "<br>File Base Name: "&FSOobj.GetBaseName(FilePath)
Response.Write "<br>File Base Name: "&FSOobj.GetBaseName("K:php_filesafile")
Else
Response.Write "File does not exist"
End if 
Set FSOobj = Nothing


Be the first to post comment on this article :

plus2net.com




Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer