OpenTextFile 方法

開啟指定的檔案,並傳回可用來讀取、寫入或附加至檔案的 TextStream 物件。

語法

object.OpenTextFile(filename[, iomode[, create]])

引數:

  • Object必要。此物件一律是 FileSystemObject 的名稱。
  • Filename必要。識別要開啟之檔案的字串表示式。
  • Iomode選擇性。可以是三個常數之一:ForReading、ForWriting 或 ForAppending。
  • Create選擇性。指出如果指定的檔案名稱不存在,是否可以建立新檔案的布林值。如果建立新檔案,則值為 True,如果未建立,則為 False。如果省略,則不會建立新檔案。
  • Format選擇性。指出開啟檔案的格式。

    註:

    Format 引數為靜止狀態並保持模擬 VB 指令碼語法。它沒有作用。所有建立的檔案只會是 Unicode 格式。

設定值

iomode 引數可具有下列任一設定值:

表格 11-34 IOMode 引數設定值

常數 描述
ForReading 1 開啟檔案僅供唯讀。無法寫入此檔案。
ForWriting 2 開啟檔案以供寫入。
ForWriting 8 開啟檔案並寫入檔案結尾。

備註

下列程式碼說明 OpenTextFile 方法的用法。

註:

  • 如果建立新檔案,將會以 Unicode 格式建立該檔案。

  • 如果檔案不存在,程式碼將在 ReadMode 中擲出錯誤。

範例 1

Sub OpenFileForReading()
    Const ForReading = 1
    Dim fso, tso
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set tso = fso.OpenTextFile("C:\example1.txt", ForReading)    
    tso.Close               ' Close the file.

    Set tso = Nothing
    Set fso = Nothing
End Sub

Call OpenFileForReading
'If C:\example1.txt is not present then code will throw an error. 

範例 2

Sub OpenFileForWriting()
    Const ForWriting = 2
    Dim fso, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile("C:\example2.txt", ForWriting, True)
    
    file.WriteLine("This is written to the file.")   ' Writes text to the file.
    file.Close               ' Close the file.

    Set file = Nothing
    Set fso = Nothing
End Sub

Call OpenFileForWriting
'Creates C:\example2.txt and writes a line "This is written to the file."

範例 3

Sub OpenFileForAppending()
    Const ForAppending = 8
    Dim fso, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile("C:\example2.txt", ForAppending, True)
    
    file.WriteLine("This line is appended.")   ' Appends text to the file.
    file.Close               ' Close the file.

    Set file = Nothing
    Set fso = Nothing
End Sub

Call OpenFileForAppending
'Creates C:\example2.txt and writes a line "This line is appended.". If file already exists it appends this line.

範例 4

Sub OpenFileWithCreateOption()
    Const ForWriting = 2
    Dim fso, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile("C:\example2.txt", ForWriting, True)   ' Creates the file if it doesn't exist.

    file.WriteLine("New File created and text written.")   ' Writes text to the file.
    file.Close               ' Close the file.
 
    Set file = Nothing
    Set fso = Nothing
End Sub

Call OpenFileWithCreateOption
'Overwrites C:\example2.txt and writes a line "New File created and text written.". If file does not exists then it creates it.