開啟指定的檔案,並傳回可用來讀取、寫入或附加至檔案的 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