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

如果覆寫引數為 false,則表示已經存在的檔案名稱會發生錯誤。

範例 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