Friday 5 November 2010

ASP: Scripting.FileSystemObject OpenTextFile vs Server-Side Include

   


In this short post I would like to compare two ways of including a file in an asp page. As you may be all aware, we can include a file into a page using a server-side include like:
<!--#include virtual="/example.txt" -->
In the page containing the above code, all the content of the txt file will be displayed.
If the content of the example.txt file is:
<table border="1"><tr><td>Hello!</td></tr></table>

I
am
Denny
Crane!
the result in page (using the above server-side include) will be:

Hello!
I am Denny Crane!
Notice that all the line breaks are not considered, while the table is perfectly rendered.
Now, if instead of using the server-side include, we use the FileSystemObject and specifically its OpenTextFile method, the result will be different, because we can use the command to actually read the txt content line by line.
<%
Const ForReading = 1
Const Create = False

Dim objFSO
Dim TS
Dim strLine
Dim strFileName
strFileName = Server.MapPath("example.txt")

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

If (objFSO.FileExists(strFileName)) then
Set TS = objFSO.OpenTextFile(strFileName, ForReading, Create)

If Not TS.AtEndOfStream  Then

 Do While Not TS.AtendOfStream

  strLine = TS.ReadLine
  Response.Write strLine
  Response.Write "<br>"

 Loop

End If

TS.Close
Set TS = Nothing
end if
Set objFSO = Nothing%>
Using the above code, the result will be:

Hello!


I
am
Denny
Crane!

Which is exactly what is on the txt file, including line breaks.

This result show us the main difference between server-side include and Scripting.FileSystemObject. In my opinion, the second method is much more flexible and it can be used in various situations.
I have to add that, in addition to reading the file content, you can actually modify it quite simply. The line
Set TS = objFSO.OpenTextFile(strFileName, ForReading, Create)
Can be changed to:
Set TS = objFSO.OpenTextFile(strFileName, 2, True)
In order to delete the whole content of the file and replace it with a new text with:
TS.WriteLine("Hello World!")
At the same time you can append text to your file using:
Set TS = objFSO.OpenTextFile(strFileName, 8, True)

As you can see the above code snippets open new possibilities. Now your imagination is the limit. Let me know what you think about it.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.