打开指定的文件,并返回可用于从该文件读取、写入该文件或附加到该文件的 TextStream 对象。
语法
object.OpenAsTextStream([iomode, [format]])
参数:
Object:必需。始终为 File 对象的名称。
Iomode:可选。指示输入/输出模式。可以是以下三个常量之一:ForReading、ForWriting 或 ForAppending。
Format:可选。指示打开文件的格式。如果省略,则默认情况下文件以 Unicode 格式打开。
Note:
Format 参数处于休眠状态,并保留以模仿 VB 脚本行为。它没有任何效果。创建的所有文件仅采用 Unicode 格式。
设置
iomode 参数可以具有以下任何设置:
Table 11-35 Iomode 参数设置
| 常量 | 值 | 说明 |
|---|---|---|
| ForReading | 1 | 打开仅供读取的文件。您无法写入此文件。 |
| ForWriting | 2 | 打开供写入的文件。 |
| ForAppending | 8 | 打开文件并写入文件的末尾。 |
注释
OpenAsTextStream 方法提供的功能与 FileSystemObject 的 OpenTextFile 方法的功能相同。此外,可以使用 OpenAsTextStream 方法写入文件。
以下代码说明了 OpenAsTextStream 方法的用法:
示例 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."
示例 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."
示例 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."
示例 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