ASP File OperationsTry the demo or view the source code.
TextStream object which can then be used to read from or
write to the file. A short overview of each method is given below.
||Returns the specified number of characters.|
||Returns all characters up to but not including the next newline character.|
||Returns all characters in the file.|
||Skips over the specified number of characters.|
||Skips all characters up to and including the next newline character.|
||Writes the given text string to the file.|
||Writes the given text string to the file followed by a newline character.|
||Writes the given number of newline characters to the file.|
||Closes the file.|
Using each file mode, three separate routines can be defined to read, write or append to a text file. Constants are defined for each mode value to improve readability.
Note that all input and output is done one line at a time.
<% Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 %> <% 'Open and read a text file. set fs = CreateObject("Scripting.FileSystemObject") set file = fs.OpenTextFile(path, ForReading) do while not file.AtEndOfStream Response.Write(file.ReadLine & vbCrLf) loop file.Close() %> <% 'Overwrite a text file. set fs = CreateObject("Scripting.FileSystemObject") set file = fs.OpenTextFile(path, ForWriting) file.WriteLine("Overwriting file with this text.") file.Close() %> <% 'Append to an existing text file. set fs = CreateObject("Scripting.FileSystemObject") set file = fs.OpenTextFile(path, ForAppending) file.WriteLine("This line is added to the file.") file.Close() %>
The demo implements all five operations: create, delete, read, write and append, as subroutines. Using the form provided, you can run each one against a sample text file and see the results.
Although only limited error checking is done by these routines, they do make
use of the
FileExists() method to give informational messages
should you attempt an invalid operation, such as deleting the file and then
trying to open it for reading.