Apre un file specificato e restituisce un oggetto TextStream che può essere utilizzato per eseguire operazioni di lettura, scrittura o aggiunta a livello di file.
Sintassi
object.OpenTextFile(filename[, iomode[, create]])
Argomenti:
FileSystemObject.Format: facoltativo. Indica il formato del file aperto.
Nota:
L'argomento format è inattivo e viene mantenuto come riferimento alla sintassi dello script VB. Non ha alcun effetto. Tutti i file creati vengono creati solo in formato Unicode.
Impostazioni
L'argomento iomode può avere una delle seguenti impostazioni:
Tabella 11-34 Impostazione dell'argomento IOMode
| Costante | Valore | Descrizione |
|---|---|---|
| ForReading | 1 | Apre il file in sola lettura. Non è possibile scrivere in questo file. |
| ForWriting | 2 | Apre il file in modalità di scrittura. |
| ForWriting | 8 | Apre il file consentendone la scrittura alla fine del file. |
Note
Nel codice seguente viene illustrato l'uso del metodo OpenTextFile.
Nota:
Se viene creato un nuovo file, il file verrà creato in formato Unicode.
Se il file non esiste, il codice restituirà un errore in ReadMode.
Esempio 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.
Esempio 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."
Esempio 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.
Esempio 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.