CreateTextFile Method

Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.

Syntax

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

Arguments

  • Object: Required. Always the name of a FileSystemObject.
  • Filename: Required. String expression that identifies the file to create.
  • Overwrite: Optional. Boolean value that indicates whether you can overwrite an existing file. The value is true if the file can be overwritten, false if it can't be overwritten.
  • Unicode: Optional. Boolean value that indicates whether the file is created as a Unicode or ASCII file. The value is true if the file is created as a Unicode file, false if it's created as an ASCII file.

    Note:

    Unicode argument is dormant and kept to mimic VB script syntax. It has no effect. All the files created are in Unicode format only.

Remarks

The following code illustrates how to use the CreateTextFile method to create and open a text file.

Example 1:

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

If the overwrite argument is false, for a filename that already exists, an error occurs.

Example 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

Example 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