ASP File Operations
Try the demo or view the source code.Like CreateTextFile(),
the OpenTextFile()
method
returns a TextStream
object which can then be used to read from or
write to the file. A short overview of each method is given below.
TextStream Methods | |
---|---|
Method | Description |
Read(n) |
Returns the specified number of characters. |
ReadLine() |
Returns all characters up to but not including the next newline character. |
ReadAll() |
Returns all characters in the file. |
Skip(n) |
Skips over the specified number of characters. |
SkipLine() |
Skips all characters up to and including the next newline character. |
Write(str) |
Writes the given text string to the file. |
WriteLine(str) |
Writes the given text string to the file followed by a newline character. |
WriteBlankLines(n) |
Writes the given number of newline characters to the file. |
Close() |
Closes the file. |
Example Code
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.