Abre um arquivo especificado e retorna um objeto TextStream que pode ser usado para ler, gravar ou anexar ao arquivo.
Sintaxe
object.OpenTextFile(filename[, iomode[, create]])
Argumentos:
FileSystemObject.Format: Opcional. Indica o formato do arquivo aberto.
Nota:
O argumento format está inativo e é mantido para imitar a sintaxe do VB Script. Ele não tem efeito. Todos os arquivos são criados no formato Unicode.
Configurações
O argumento iomode pode ter as seguintes configurações:
Tabela 11-34 Configurações do Argumento IOMode
| Constante | Valor | Descrição |
|---|---|---|
| ForReading | 1 | Abre um arquivo somente para leitura. Você não pode gravar neste arquivo. |
| ForWriting | 2 | Abre um arquivo para gravação. |
| ForWriting | 8 | Abre um arquivo e grava no final do arquivo. |
Comentários
O código a seguir ilustra o uso do método OpenTextFile.
Nota:
Se um Arquivo for criado, será criado com o formato Unicode.
Se o Arquivo não existir, o código gerará um erro em ReadMode.
Exemplo 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.
Exemplo 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."
Exemplo 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.
Exemplo 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.