Apr 24, 2008

How to write text file using ASP?

How to write text file using ASP?

Previously I wrote for how to write text file with C#, Now one step back how to write text file with ASP?

So here we goes.

set FSO = Server.CreateObject("scripting.FileSystemObject")

This line creates an object that is used for File Access

set myFile = fso.CreateTextFile("C:\Trace.txt", true)

This creates a blank text file object for us to use.The CreateTextFile object creates a text file, based on what we specified. The first option specifies the location of the text file, while the second one states whether or not to create the file if one doesn't exist. Very simple methods.

Next, we do something simple

myFile.WriteLine("Write whatever you want to put")

myFile.WriteLine("Write some more stuff")

WriteLine writes the text to the text file.

myFile.Close

This closes the file and free the memory.

Now for Reading:

First, we create an object, but not after defining some constants

Const ForReading = 1, ForWriting = 2, ForAppending = 8

This just allows us the different methods of working with text, when we have an open text file.

set fso = server.CreateObject("Scripting.FileSystemObject")

Here we create our object again.

set f = fso.GetFile("C:\Trace.txt")

Here we state that we will be manipulating the file C:\Trace.txt . Moderately simple. Now we need to open it as a stream. Get ready, here comes the hard stuff ;-)

set ts = f.OpenAsTextStream(ForReading, -2)

This creates a text stream with our file. It is like a continous flow of information. Now we jsut read a line

TextStreamTest = ts.ReadLine

This code reads a line of information, and puts it into TextStreamTest. Pretty simple, isnt it?! I hope so. Anyway, I've discussed the code, and I shall let you go.

One last note. Let's say you wanted to read all the contents out a text file. Then you would do this

Do While not ts.AtEndOfStream

myText = myText & ts.ReadLine & vbCrLf

Loop

Hope you learn something !! Write your comments !! Thanks !!

No comments:

Post a Comment

SQL - Difference between CAST,CONVERT and PARSE

TODO---