C # in a Nutshell, Second Edition

BinaryReader CF 1.0, disposable

System.IO (mscorlib.dll) class

This class allows you to read data from a Stream . When using a BinaryReader , the data represented by a Stream is regarded as a binary format, and bits are merely read from the stream and copied into the appropriate types. The methods prefixed with Read( ) allow you to grab data of a specific type from the front of the Stream and advance the current position. The next table shows how many bytes each of these methods reads in from a stream.

Method

Bytes read

Method

Bytes read

Read

variable

ReadInt32

4

ReadBoolean

1

ReadInt64

8

ReadByte

1

ReadSByte

1

ReadBytes

variable

ReadSingle

4

ReadChar

2

ReadString

variable

ReadChars

variable

ReadUInt16

2

ReadDecimal

16

ReadUInt32

4

ReadDouble

8

ReadUInt64

8

ReadString( ) uses the current encoding of the BinaryReader , which can be set when you call the constructor. Strings are prefixed with their length. PeekChar( ) allows you to look at the first character of a stream (a System.Char , which is two bytes) without advancing the position of the Stream . Because a binary reader may hold on to resources that should be freed when not needed, the BinaryReader must be closed using Close( ) or by wrapping it in a using block (which calls the protected Dispose( ) method to do the cleanup at the end of the using block).

public class BinaryReader : IDisposable { // Public Constructors public BinaryReader (Stream input ); public BinaryReader (Stream input , System.Text.Encoding encoding ); // Public Instance Properties public virtual Stream BaseStream {get; } // Public Instance Methods public virtual void Close ( ); public virtual int PeekChar ( ); public virtual int Read ( ); public virtual int Read (byte[ ] buffer , int index , int count ); public virtual int Read (char[ ] buffer , int index , int count ); public virtual bool ReadBoolean ( ); public virtual byte ReadByte ( ); public virtual byte[ ] ReadBytes (int count ); public virtual char ReadChar ( ); public virtual char[ ] ReadChars (int count ); public virtual decimal ReadDecimal ( ); public virtual double ReadDouble ( ); public virtual short ReadInt16 ( ); public virtual int ReadInt32 ( ); public virtual long ReadInt64 ( ); public virtual sbyte ReadSByte ( ); public virtual float ReadSingle ( ); public virtual string ReadString ( ); public virtual ushort ReadUInt16 ( ); public virtual uint ReadUInt32 ( ); public virtual ulong ReadUInt64 ( ); // Protected Instance Methods protected virtual void Dispose (bool disposing ); protected virtual void FillBuffer (int numBytes ); protected int Read7BitEncodedInt ( ); }

Категории