Input & Output
This chapter is dedicated to Input & Output in Visual Basic. The Input & Output in Visual Basic is based on streams.Streams are objects to work with Input/Output. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. In Visual Basic, we have a
Stream
class, that is an abstract class
for all streams. There are additional classes that derive from the Stream
class and make the programming a lot easier.
MemoryStream
AMemoryStream
is a stream which works with
data in a computer memory.
Option Strict On Imports System.IO Module Example Sub Main() Dim ms As Stream = New MemoryStream(6) ms.WriteByte(9) ms.WriteByte(11) ms.WriteByte(6) ms.WriteByte(8) ms.WriteByte(3) ms.WriteByte(7) ms.Position = 0 Dim rs As Integer rs = ms.ReadByte() Do While rs <> -1 Console.WriteLine(rs) rs = ms.ReadByte() Loop ms.Close() End Sub End ModuleWe write six numbers to a memory with a
MemoryStream
.
Then we read those numbers and print them to the console.
Dim ms As Stream = New MemoryStream(6)The line creates and initializes a
MemoryStream
object with a capacity of six bytes.
ms.Position = 0We set the position of the cursor in the stream to the beginning using the
Position
property.
ms.WriteByte(9) ms.WriteByte(11) ms.WriteByte(6) ...The
WriteByte()
method writes a byte to the current
stream at the current position.
Do While rs <> -1 Console.WriteLine(rs) rs = ms.ReadByte() LoopHere we read all bytes from the stream and print them to the console.
ms.Close()Finally, we close the stream.
$ ./memory.exe 9 11 6 8 3 7Output of the example.
No comments: