OpenAsTextStream Method
Opens a specified file and returns a TextStream
object that can be
used to read from, write to, or append to the file.
Syntax
object.OpenAsTextStream([iomode, [format]])
Arguments:
-
Object: Required. Always the name of a File object.
-
Iomode: Optional. Indicates input/output mode. Can be one of three constants: ForReading, ForWriting, or ForAppending.
-
Format: Optional. Indicate the format of the opened file. If omitted, the file is opened as Unicode by default.
Note:
Format argument is dormant and kept to mimic VB script behavior. It has no effect. All the files created are in Unicode format only.
Settings
The iomode argument can have any of the following settings:
Table 11-35 The Iomode argument setting
Constant | Value | Description |
---|---|---|
ForReading | 1 | Open a file for reading only. You can't write to this file. |
ForWriting | 2 | Open a file for writing. |
ForAppending | 8 | Open a file and write to the end of the file. |
Remarks
The OpenAsTextStream
method provides the same functionality as the
OpenTextFile
method of the FileSystemObject
.
In addition, the OpenAsTextStream
method can be used to write to a
file.
The following code illustrates the use of the OpenAsTextStream
method:
Example 1
Function WriteToFile(filepath, text)
Const ForWriting = 2
Dim fso, f, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filepath)
Set ts = f.OpenAsTextStream(ForWriting)
ts.Writeline text
ts.Close
End Function
' Usage
WriteToFile "C:\Path\To\Your\File.txt", "This is a test message."
Example 2:
Function AppendToFile(filepath, text)
Const ForAppending = 8
Dim fso, f, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filepath)
Set ts = f.OpenAsTextStream(ForAppending)
ts.WriteLine text
ts.Close
End Function
' Usage
AppendToFile "C:\Path\To\Your\File.txt", "This is additional text."
Example 3:
Function WriteUnicodeToFile(filepath, text)
Const ForWriting = 2
Const TristateTrue = -1
Dim fso, f, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filepath)
Set ts = f.OpenAsTextStream(ForWriting, TristateTrue)
ts.Writeline text
ts.Close
End Function
' Usage
WriteUnicodeToFile "C:\Path\To\Your\File.txt", "This is a Unicode test message."
Example 4:
Function ReadFromFile(filepath)
Const ForReading = 1
Dim fso, f, ts, content
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filepath)
Set ts = f.OpenAsTextStream(ForReading)
Do While Not ts.AtEndOfStream
content = content & ts.ReadLine
Loop
ts.Close
ReadFromFile = content
End Function
' Usage
Dim fileContent
fileContent = ReadFromFile("C:\Path\To\Your\File.txt")
'Output: Content of the File