OpenTextFile 方法

打开指定的文件,并返回可用于从该文件读取、写入该文件或附加到该文件的 TextStream 对象。

语法

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

参数:

  • Object必需。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.