BinaryReader: ReadString

ReadString

Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.



 Public Function ReadString ( ) As String

Return Values

String -  The string datatype.

Remarks

BinaryReader does not restore the file position after an unsuccessful read.

The string is stored in the stream with the number of encoded bytes preceding the actual string data. The bytes are not the typical 4 bytes as is used by Visual Basci when representing the length of the string. The bytes represent a value encoded as 7 bits per byte. While the next read byte has the high bit set (&H80), then the following byte is also part of the length value. For each byte read, first 7 bits of that byte is pushed out 7 bits multiplied by the current byte number - 1 in the sequence. This is not the normal shifting of the current sum of the values. Each read byte must be shifted left individually, as each byte represents a higher set of bits in the resulting number.

We AND the byte with &H3f because we only want the lower 7 bits.
byte 1: (byte and &H3f) << shifted 0 bits added to the sum
byte 2: (byte and &H3f) << shifted 7 bits added to the sum
byte 3: (byte and &H3f) << shifted 14 bits added to the sum

this continues until a byte with a value less than 128 is encountered. At which point, it is shifted and summed like the rest, but no more bytes are to be read in. The sum now contains the number of bytes to be read in and decoded into the string. The Encoding used to write the original string should be used to retrieve the string. Using a different Encoding may return a corrupt string.

Once the length is determined then enough bytes are read in that can be decoded to the string using the specified Encoding.

Exceptions

Exception Condition
EndOfStreamExceptionThe end of the stream is reached.
ObjectDisposedExceptionThe stream is closed.
IOExceptionAn I/O error occurs.

See Also

Project CorLib Overview

Class BinaryReader Overview