Example Code:
Set objFSO = CreateObject("Scripting.FileSystemObject")
strPath = "C:\FSO"
strFileName = objFSO.GetTempName
strFullName = objFSO.BuildPath(strPath, strFileName)
Set objFile = objFSO.CreateTextFile(strFullName)
objFile.Close
1.
Create an instance of the FileSystemObject.
2.
Use the OpenTextFile method to open the text file. The OpenTextFile method requires two parameters: the path to the file and one of the following values:
•
For reading (parameter value = 1, constant = ForReading). Files opened in this mode can only be read from. To write to the file, you must open it a second time by using either the ForWriting or ForAppending mode.
•
For writing (parameter value 2, constant = ForWriting). Files opened in this mode will have new data replace any existing data. (That is, existing data will be deleted and the new data added.) Use this method to replace an existing file with a new set of data.
•
For appending (parameter value 8, constant = ForAppending). Files opened in this mode will have new data appended to the end of the file. Use this method to add data to an existing file.
You must use the appropriate parameter when opening the file. For example, if you open a file for reading and then attempt to write to the file, you will receive a "Bad file mode" error. You will also receive this error if you attempt to open anything other than a plain-text file. (It is worth noting that both HTML and XML files are plain-text files.)
You can use either the parameter value (for example, 1 for reading) or you can create a constant and set the value appropriately. For example, both of these methods will open a file for reading:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", ForReading)
Set objFile2 = objFSO.OpenTextFile("C:\FSO\ScriptLog2.txt", 1)
However, you cannot use the constants without first defining them. This is due to the fact that VBScript does not have intrinsic access to COM object constants. The following script sample will fail and return an "Invalid procedure call or argument" error because the ForReading constant has not been explicitly defined. Because it has not been defined, ForReading is automatically assigned the value 0, and 0 is not a valid parameter for OpenTextFile.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", ForReading)
The script in Listing 4.35 opens C:\FSO\ScriptLog.txt for reading, using the user-defined constant ForReading to represent the value 1.
Listing 4.35 Opening a Text File for Reading
1
2
3
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", ForReading)
|