|
A quick review of Visual Basic TextStream Object
The article discusses various Methods & properties of Text Stream object in the context of handling a text file)
-- by Mahipal Padigela
A quick review of Visual Basic TextStream Object
The TextStream Object facilitates sequential access to a text file.
The FileSystemObject(FSO) returns TextStream object when you open or create a text file.
You need to reference 'Microsoft Scripting runtime' Object library to your project before TextStreams.
The next two lines of code declare two object variables to hold FSO and TextStream Objects.
Dim myFSO As New FileSystemObject
Dim myTextStream As TextStream
Opening and Reading a text file
The next line of code returns a TextStream Object to myTextStream variable from the FileSystemObject (myFSO)
Set myTextStream = myFSO.OpenTextFile("C:\test.txt", 1)
Possible values for the second parameter are ForReading = 1, ForWriting = 2, ForAppending = 8
Reading entire contents of a text file into a variable(Note:For large files,wastes memory resources)
strTextInFile = myTextStream.ReadAll
Reading a specified number of characters from the text file
myTextStream.Read (n)
where 'n' is the number of characters you want to read from the beginning of file
Skipping a specified number of characters from the text file
myTextStream.Skip (n)
where 'n' is the number of characters you want to SKIP from the beginning of file
Skipping the next line when Reading
myTextStream.SkipLine
Reading the contents of text file Line by Line
Do Until myTextStream.AtEndOfStream 'you can also use Do Until myTextStream.AtEndOfLine
strLine = myTextStream.ReadLine
Loop
Creating and Writing to a text file
The next line of code creates a text file and returns a TextStream Object to myTextStream variable from the FileSystemObject (myFSO)
Set myTextStream = myFSO.CreateTextFile("C:\test.txt", True)
True Overwrites if the file already exists
Writing some text to a text file
myTextStream.Write strSomeText
Writing a line to a text file
myTextStream.WriteLine strOneline
Writes a specified number of newline characters(blank lines)
myTextStream.WriteBlankLines (2)
Closing the TextStream and release the references
myTextStream.Close
Set myFSO = Nothing
Set myTextStream = Nothing
|