CreateTextFile 方法

创建指定的文件名,并返回可用于从该文件读取或写入该文件的 TextStream 对象。

语法

object.CreateTextFile(filename[, overwrite[, unicode]])

参数

  • Object必需。始终为 FileSystemObject 的名称。
  • Filename必需。用于标识要创建的文件的字符串表达式。
  • Overwrite可选。指示是否可以覆盖现有文件的布尔值。如果可以覆盖文件,则值为 true;如果无法覆盖,则值为 false。
  • Unicode可选。指示文件是创建为 Unicode 文件还是 ASCII 文件的布尔值。如果文件创建为 Unicode 文件,则值为 true;如果文件创建为 ASCII 文件,则值为 false。

    注:

    Unicode 参数处于休眠状态,并保留以模仿 VB 脚本语法。它没有任何效果。创建的所有文件仅采用 Unicode 格式。

注释

以下代码说明如何使用 CreateTextFile 方法创建和打开文本文件。

示例 1

Sub CreateAfile
   Dim fso, tso
  Set fso = CreateObject("Scripting.FileSystemObject")
   Set tso = fso.CreateTextFile("c:\testfile.txt", True)   
   tso.Close
End Sub
CreateAfile

如果 overwrite 参数为 false,则对于已存在的 filename,会出现错误。

示例 2:CreateNewFile

Sub CreateNewFile()
    Dim fso, tso
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set tso = fso.CreateTextFile("C:\example1.txt", True)   ' Overwrites if the file exists.
    tso.WriteLine("This is a new text file.")   ' Write some text to the file.
    tso.Close   ' Close the file.
     Set fso = Nothing
End Sub
CreateNewFile

示例 3

Sub CreateFileNoOverwrite ()
    Dim fso, tso
    Set fso = CreateObject("Scripting.FileSystemObject")
    On Error Resume Next
    Set tso = fso.CreateTextFile("C:\Temp\testfile.txt", False)   ' Do not overwrite if the file exists.
    myerr = Err.Number
    If myerr <> 0 Then
        ‘Error handling code File already exists and won't be overwritten."
    Else
        tso.WriteLine("This file won't be overwritten if it exists.")   ' Write some text to the file.
        tso.Close   ' Close the file. 
    End If
    Err.Clear
    On Error GoTo 0
    Set fso = Nothing
End Sub

CreateFileNoOverwrite