How To Manipulate Text Files in an ASP Page

Summary

This article describes how to create, write, read, move, copy, and delete text files from within an Active Server Pages (ASP) page.

You may want to use a text file for the sake of simplicity (when a database or more complicated file format may be excessive) or when prior data exists in the form of text files. Typical scenarios include:
  • Reading or writing a flat file that a mainframe, third-party application, or trading partner creates or uses.
  • Dynamically generating Windows batch or script files based on parameters that a client application supplies.
The Scripting.FileSystemObject Component Object Model (COM) object exposes a rich set of features to manipulate drives, folders, and files. This FileSystemObject (FSO) object is implemented within an in-process COM server called ScrObj.dll. This article only explores the file manipulation features of the FSO object model.

Requirements

Your computer should be running either:

  • Microsoft Internet Information Server (IIS) 4.0 and Active Server Pages (ASP) 2.0.
  • Internet Information Services 5.0 and Active Server Pages 3.0.
You can use the general techniques, if not the implementation details, with any scripting language that supports Microsoft COM technology; they are also not restricted to ASP.

It is helpful if you are familiar with VBScript or JScript.

Create the FileSystemObject

Before you manipulate text files, create the FSO as follows:

VBScript Code
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
JScript Code
var objFSO;
objFSO = new ActiveXObject("Scripting.FileSystemObject");

How to Create, Open, and Delete Text Files

The FSO exposes the CreateTextFile method, which enables you to create an empty text file. It also exposes the OpenTextFile and DeleteFile methods, which enable you to open or delete an existing file respectively. Alternatively, you can use the File object to perform each of these three operations. To obtain an instance of the File object, invoke the GetFile method of the FSO. However, this article only demonstrates the direct methods on the FSO. Please refer to the "References" section for more information about the File object techniques.

The OpenTextFile method enables files to be opened for reading, writing, or appending textual information.

VBScript Code
Dim objFSO, objCreatedFile, objOpenedFile
Const ForReading = 1, ForWriting = 2, ForAppending = 8

'Create the FSO.
Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objCreatedFile = objFSO.CreateTextFile("c:\HowToDemoFile.txt", True)
Set objOpenedFile = objFSO.OpenTextFile("c:\HowToDemoFile2.txt", ForWriting, True)

'Use objCreatedFile and objOpenedFile to manipulate the corresponding files.
objCreatedFile.Close
objOpenedFile.Close

'Delete the files.
objFSO.DeleteFile "c:\HowToDemoFile.txt"
objFSO.DeleteFile "c:\HowToDemoFile2.txt"
JScript Code
var objFSO, objCreatedFile, objOpenedFile;
var ForReading = 1, ForWriting = 2, ForAppending = 8;

// Create the FSO.
objFSO = new ActiveXObject("Scripting.FileSystemObject");

objCreatedFile = objFSO.CreateTextFile("c:\\HowToDemoFile.txt", true);
objOpenedFile = objFSO.OpenTextFile("c:\\HowToDemoFile2.txt", ForWriting, true);

// Use objCreatedFile and objOpenedFile to manipulate the corresponding files.
objCreatedFile.Close();
objOpenedFile.Close();

// Delete the files.
objFSO.DeleteFile("c:\\HowToDemoFile.txt");
objFSO.DeleteFile("c:\\HowToDemoFile2.txt");

How to Write to and Read from a Text File

The CreateTextFile or OpenTextFile methods of the FSO return an instance of the TextStream object, which exposes methods to write or read text files.

Both the Write and WriteLine methods add text to an open file, but WriteLine also appends a trailing newline character. The WriteBlankLines method writes one or more blank lines to an open file based on the parameter that is specified.

The Read method reads the specified number of characters from the current position in the open file. The ReadLine method reads an entire line (up to, but excluding, the newline character), whereas the ReadAll method reads the entire contents of the open file. All three of these methods store the resulting text in a string that you can easily manipulate with various string manipulation operations.

The following code demonstrates these methods:

VBScript Code
Dim objFSO, objTextFile
Dim sRead, sReadLine, sReadAll
Const ForReading = 1, ForWriting = 2, ForAppending = 8

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile("c:\HowToDemoFile.txt", True)

' Write a line with a newline character.
objTextFile.WriteLine("This line is written using WriteLine().")

' Write a line.
objTextFile.Write ("This line is written using Write().")

' Write three newline characters to the file.
objTextFile.WriteBlankLines(3)

objTextFile.Close

' Open file for reading.
Set objTextFile = objFSO.OpenTextFile("c:\HowToDemoFile.txt", ForReading)

' Use different methods to read contents of file.
sReadLine = objTextFile.ReadLine
sRead = objTextFile.Read(4)
sReadAll = objTextFile.ReadAll

objTextFile.Close
JScript Code
var objFSO, objTextFile;
var sRead, sReadLine, sReadAll;
var ForReading = 1, ForWriting = 2, ForAppending = 8;

objFSO = new ActiveXObject("Scripting.FileSystemObject");
objTextFile =objFSO.CreateTextFile("c:\\HowToDemoFile.txt", true);

// Write a line with a newline character.
objTextFile.WriteLine("This line is written using WriteLine().");

// Write three newline characters to the file.
objTextFile.WriteBlankLines(3);

// Write a line.
objTextFile.Write ("This line is written using Write().");
objTextFile.Close();

// Open file for reading.
objTextFile = objFSO.OpenTextFile("c:\\HowToDemoFile.txt", ForReading);

// Use different methods to read contents of file.
sReadLine = objTextFile.ReadLine();
sRead = objTextFile.Read(4);
sReadAll = objTextFile.ReadAll();

objTextFile.Close();

How to Move and Copy Text Files

The FSO exposes the MoveFile and CopyFile methods, which enable you to move and copy files respectively. Alternatively, you can use the File object to perform each of these two operations. To obtain an instance of the File object, invoke the GetFile method of the FSO. However, this article only demonstrates the direct methods on the FSO. Please refer to the "References" section for more information about the File object techniques.

The following code sample demonstrates these methods:

VBScript Code
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")

objFSO.MoveFile "c:\HowToDemoFile.txt", "c:\Temp\"
objFSO.CopyFile "c:\Temp\HowToDemoFile.txt", "c:\"
JScript Code
var objFSO;
objFSO = new ActiveXObject("Scripting.FileSystemObject");

objFSO.MoveFile("c:\\HowToDemoFile.txt", "c:\\Temp\\");
objFSO.CopyFile("c:\\Temp\\HowToDemoFile.txt", "c:\\");

Troubleshooting

  • Error messages while creating Scripting.FileSystemObject:

    This problem most likely occurs because of the following scenarios:

    • ScrObj.dll has not been installed on the deployment computer.
    • ScrObj.dll has been accidentally deleted.
    • ScrObj.dll has been accidentally unregistered from the COM registry.

    Because ScrObj.dll resides in the <Windows Installation Directory>\System32 folder, it is part of the operating system dynamic-link libraries (DLLs). Thus, on Windows 2000-based computers, it cannot be deleted, at least not without resorting to extreme measures that seriously hamper the system.
  • Error messages while performing file manipulation operations:

    If drives are formatted using the NTFS file system, users in the Administrator group have control over security permissions for entire drives, folders, and files. Especially on Web servers, Administrators should enforce strong security permissions to prevent illegal access to files and information. When you design and write an ASP application that uses the above-mentioned file manipulation techniques, special consideration should be given to the security permissions for the file system on deployment computers to prevent errors that are related to insufficient security permissions.

References

For more information about scripting, see the following MSDN Web sites: You can also refer to these topics in the April 2001 MSDN CD under "Platform SDK Documentation" in the following folders:
Tools and Scripting\Scripting\Scripting Runtime\FileSystemObject Object
Proprietăți

ID articol: 300982 - Ultima examinare: 27 nov. 2008 - Revizie: 1

Feedback