System.IO.BufferedStream Class

Assembly: Mscorlib.dll
Namespace: System.IO
Summary
Reads and writes to another stream. This class cannot be inherited.
C# Syntax:
public sealed class BufferedStream : Stream
Remarks
A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. Buffers thus improve read and write performance. A buffer can be used for either reading or writing, but never both simultaneously. The BufferedStream.Read and BufferedStream.Write methods of BufferedStream automatically maintain the buffer.

BufferedStream can be composed around certain types of streams. It provides implementations for reading and writing bytes to an underlying data source or repository. Use BinaryReader and BinaryWriter for reading and writing other data types.BufferedStream is designed to prevent the buffer from slowing down input and output when the buffer is not needed. If you always read and write for sizes greater than the internal buffer size, then BufferedStream might not even allocate the internal buffer.BufferedStream also buffers reads and writes in a shared buffer. It is assumed that you will almost always be doing a series of reads or writes, but rarely alternate between the two of them.

See also:
System.IO Namespace | FileStream | MemoryStream | Stream

System.IO.BufferedStream Member List:

Public Constructors
ctor #1 Overloaded:
.ctor(Stream stream)

Initializes a new instance of the BufferedStream class with a default buffer size of 4096 bytes.
ctor #2 Overloaded:
.ctor(Stream stream, int bufferSize)

Initializes a new instance of the BufferedStream class with the specified buffer size.
Public Properties
CanRead Read-only

Overridden:
Gets a value indicating whether the current stream supports reading.
CanSeek Read-only

Overridden:
Gets a value indicating whether the current stream supports seeking.
CanWrite Read-only

Overridden:
Gets a value indicating whether the current stream supports writing.
Length Read-only

Overridden:
Gets the stream length in bytes.
Position Read-write

Overridden:
Gets the position within the current stream.
Public Methods
BeginRead
(inherited from System.IO.Stream)
See base class member description: System.IO.Stream.BeginRead


Begins an asynchronous read operation.
BeginWrite
(inherited from System.IO.Stream)
See base class member description: System.IO.Stream.BeginWrite


Begins an asynchronous write operation.
Close Overridden:
Closes the stream and releases any resources (especially system resources such as sockets and file handles) associated with the current buffered stream.
CreateObjRef
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.CreateObjRef


Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
EndRead
(inherited from System.IO.Stream)
See base class member description: System.IO.Stream.EndRead


Waits for the pending asynchronous read to complete.
EndWrite
(inherited from System.IO.Stream)
See base class member description: System.IO.Stream.EndWrite


Ends an asynchronous write operation.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
Flush Overridden:
Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.GetLifetimeService


Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
InitializeLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.InitializeLifetimeService


Obtains a lifetime service object to control the lifetime policy for this instance.
Read Overridden:
Copies bytes from the current buffered stream to an array.
ReadByte Overridden:
Reads a byte from the underlying stream and returns the byte cast to an int, or returns -1 if reading from the end of the stream.
Seek Overridden:
Sets the position within the current buffered stream.
SetLength Overridden:
Sets the length of the buffered stream.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Write Overridden:
Copies bytes to the buffered stream and advances the current position within the buffered stream by the number of bytes written.
WriteByte Overridden:
Writes a byte to the current position in the buffered stream.
Protected Methods
CreateWaitHandle
(inherited from System.IO.Stream)
See base class member description: System.IO.Stream.CreateWaitHandle


Allocates a WaitHandle object.
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.IO.BufferedStream Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the BufferedStream class with a default buffer size of 4096 bytes.
C# Syntax:
public BufferedStream(
   Stream stream
);
Parameters:

stream

The current stream.

Exceptions
Exception Type Condition
ArgumentNullException stream is null.
Remarks
A shared read/write buffer is allocated the first time a BufferedStream object is initialized with this constructor. The shared buffer is not used if all reads and writes are greater than or equal to bufferSize.

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the BufferedStream class with the specified buffer size.
C# Syntax:
public BufferedStream(
   Stream stream,
   int bufferSize
);
Parameters:

stream

The current stream.

bufferSize

The buffer size in bytes.

Exceptions
Exception Type Condition
ArgumentNullException stream is null.
ArgumentOutOfRangeException bufferSize is negative.
Remarks
A shared read/write buffer is allocated the first time a BufferedStream object is initialized with this constructor. The shared buffer is not used if all reads and writes are greater than or equal to bufferSize.

Return to top


Overridden Property: CanRead (read-only)
Summary
Gets a value indicating whether the current stream supports reading.
C# Syntax:
public override bool CanRead {get;}
Remarks
If a class derived from Stream does not support reading, calls to the BufferedStream.Read, BufferedStream.ReadByte, Stream.BeginRead, Stream.EndRead, and the Peek methods of StreamReader, StringReader, and TextReader throw a NotSupportedException.

If the stream is closed, this property returns false.

See also:
BufferedStream.Read

Return to top


Overridden Property: CanSeek (read-only)
Summary
Gets a value indicating whether the current stream supports seeking.
C# Syntax:
public override bool CanSeek {get;}
Remarks
If a class derived from Stream does not support seeking, calls to BufferedStream.Length, BufferedStream.SetLength, BufferedStream.Position, and BufferedStream.Seek throw a NotSupportedException.

If the stream is closed, this property returns false.

See also:
BufferedStream.SetLength | BufferedStream.Seek

Return to top


Overridden Property: CanWrite (read-only)
Summary
Gets a value indicating whether the current stream supports writing.
C# Syntax:
public override bool CanWrite {get;}
Remarks
If a class derived from Stream does not support writing, a call to BufferedStream.SetLength, BufferedStream.Write, or BufferedStream.WriteByte throws a NotSupportedException.

If the stream is closed, this property returns false.

See also:
BufferedStream.Write

Return to top


Overridden Property: Length (read-only)
Summary
Gets the stream length in bytes.
C# Syntax:
public override long Length {get;}
Exceptions
Exception Type Condition
IOException The underlying stream is null or closed.
NotSupportedException The stream does not support seeking.
ObjectDisposedException Methods were called after the stream was closed.

Return to top


Overridden Property: Position (read-write)
Summary
Gets the position within the current stream.
C# Syntax:
public override long Position {get; set;}
Exceptions
Exception Type Condition
ArgumentOutOfRangeException The value passed to BufferedStream.Seek is negative.
IOException An I/O error occurs, such as the stream being closed.
NotSupportedException The stream does not support seeking.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
The get accessor invokes BufferedStream.Seek to obtain the current position within the underlying stream and then adjusts this value according to the current position within the buffer.

The set accessor copies any data previously written to the buffer to the underlying stream, and then invokes BufferedStream.Seek.

Seeking to any location beyond the length of the stream is supported.

See also:
BufferedStream.CanSeek | BufferedStream.Seek

Return to top


Method: BeginRead(
   byte[] buffer,
   int offset,
   int count,
   AsyncCallback callback,
   object state
)
Inherited
See base class member description: System.IO.Stream.BeginRead

Summary
Begins an asynchronous read operation.
C# Syntax:
public virtual IAsyncResult BeginRead(
   byte[] buffer,
   int offset,
   int count,
   AsyncCallback callback,
   object state
);
Parameters:

buffer

The buffer to read the data into.

offset

The byte offset in buffer at which to begin writing data read from the stream.

count

The maximum number of bytes to read.

callback

An optional asynchronous callback, to be called when the read is complete.

state

A user-provided object that distinguishes this particular asynchronous read request from other requests.

Return Value:
An IAsyncResult that represents the asynchronous read, which could still be pending.
Exceptions
Exception Type Condition
IOException Attempted an asynchronous read past the end of the file, or a disk error occurs.
ArgumentException One or more or the arguments is invalid.
ObjectDisposedException Methods were called after the stream was closed.
NotSupportedException The current Stream implementation does not support the read operation.
Remarks
Pass the IAsyncResult return value to the Stream.EndRead method of the stream to determine how many bytes were read and to release operating system resources used for reading. You can do this either by using the same code that called BeginRead or in a callback passed to BeginRead.

The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes.

Multiple simultaneous asynchronous requests render the request completion order uncertain.

Use the Stream.CanRead property to determine whether the current instance supports reading.

If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from BeginRead. Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the threadpool thread and become visible upon a call to EndRead. Exceptions thrown by the threadpool thread will not be visible when calling Stream.EndWrite.

Return to top


Method: BeginWrite(
   byte[] buffer,
   int offset,
   int count,
   AsyncCallback callback,
   object state
)
Inherited
See base class member description: System.IO.Stream.BeginWrite

Summary
Begins an asynchronous write operation.
C# Syntax:
public virtual IAsyncResult BeginWrite(
   byte[] buffer,
   int offset,
   int count,
   AsyncCallback callback,
   object state
);
Parameters:

buffer

The buffer to write data to. This should generally be greater than 64 kilobytes.

offset

The byte offset in buffer at which to begin writing.

count

The maximum number of bytes to write.

callback

An optional asynchronous callback, to be called when the write is complete.

state

A user-provided object that distinguishes this particular asynchronous write request from other requests.

Return Value:
An IAsyncResult that represents the asynchronous write, which could still be pending.
Exceptions
Exception Type Condition
IOException Attempted an asynchronous write past the end of the file, or a disk error occurs.
ArgumentException One or more or the arguments is invalid.
ObjectDisposedException Methods were called after the stream was closed.
NotSupportedException The current Stream implementation does not support the write operation.
Remarks
Pass the IAsyncResult returned by the current method to Stream.EndWrite to ensure that the write completes and frees resources appropriately. You can do this either by using the same code that called BeginWrite or in a callback passed to BeginWrite. If an error occurs during an asynchronous write, an exception will not be thrown until EndWrite is called with the IAsyncResult returned by this method.

If a stream is writable, writing at the end of the stream expands the stream.

The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain.

Use the Stream.CanWrite property to determine whether the current instance supports writing.

If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from BeginWrite. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the threadpool thread and become visible upon a call to EndWrite. Exceptions thrown by the threadpool thread will not be visible when calling EndWrite.

See also:
Stream.EndWrite | Stream.CanWrite

Return to top


Overridden Method: Close()
Summary
Closes the stream and releases any resources (especially system resources such as sockets and file handles) associated with the current buffered stream.
C# Syntax:
public override void Close();
Exceptions
Exception Type Condition
IOException An error occurred while trying to close the stream.
Remarks
Any data previously written to the buffer is copied to the underlying data source or repository before the buffered stream is closed. Therefore, it is not necessary to call BufferedStream.Flush before invoking Close. Following a call to Close, any operations on the buffered stream might raise exceptions.

Flushing the stream will not flush its underlying encoder unless you explicitly call BufferedStream.Flush or Close. Setting StreamWriter.AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters.

Attempting to manipulate a stream after it has been closed might throw an ObjectDisposedException.

See also:
BufferedStream.Flush

Return to top


Method: CreateObjRef(
   Type requestedType
)
Inherited
See base class member description: System.MarshalByRefObject.CreateObjRef

Summary
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
C# Syntax:
public virtual ObjRef CreateObjRef(
   Type requestedType
);
Parameters:

requestedType

The Type of the object that the new ObjRef will reference.

Return Value:
Information required to generate a proxy.
Exceptions
Exception Type Condition
RemotingException This instance is not a valid remoting object.

Return to top


Method: CreateWaitHandle()
Inherited
See base class member description: System.IO.Stream.CreateWaitHandle

Summary
Allocates a WaitHandle object.
C# Syntax:
protected virtual WaitHandle CreateWaitHandle();
Return Value:
A reference to the allocated WaitHandle.
Remarks
When called for the first time, the current method creates a WaitHandle object and returns it. On subsequent calls, the CreateWaitHandle returns a reference to the same wait handle.

Use this method if you implement the asynchronous methods and require a way of blocking in Stream.EndRead or Stream.EndWrite until the asynchronous operation is complete.

Return to top


Method: EndRead(
   IAsyncResult asyncResult
)
Inherited
See base class member description: System.IO.Stream.EndRead

Summary
Waits for the pending asynchronous read to complete.
C# Syntax:
public virtual int EndRead(
   IAsyncResult asyncResult
);
Parameters:

asyncResult

The reference to the pending asynchronous request to finish.

Return Value:
The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams only return zero (0) at the end of the stream, otherwise, they should block until at least one byte is available.
Exceptions
Exception Type Condition
ArgumentNullException asyncResult is null.
ArgumentException asyncResult did not originate from a Stream.BeginRead method on the current stream.
Remarks
Call EndRead to determine how many bytes were read from the stream.

EndRead can be called once on every IAsyncResult from Stream.BeginRead.

This method blocks until the I/O operation has completed.

Return to top


Method: EndWrite(
   IAsyncResult asyncResult
)
Inherited
See base class member description: System.IO.Stream.EndWrite

Summary
Ends an asynchronous write operation.
C# Syntax:
public virtual void EndWrite(
   IAsyncResult asyncResult
);
Parameters:

asyncResult

A reference to the outstanding asynchronous I/O request.

Exceptions
Exception Type Condition
ArgumentNullException asyncResult is null.
ArgumentException asyncResult did not originate from a Stream.BeginWrite method on the current stream.
Remarks
EndWrite must be called exactly once on every IAsyncResult from Stream.BeginWrite.

This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the threadpool thread and become visible upon a call to EndWrite. Exceptions thrown by the threadpool thread will not be visible when calling EndWrite.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~BufferedStream();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: Flush()
Summary
Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
C# Syntax:
public override void Flush();
Exceptions
Exception Type Condition
IOException The data source or repository is not open.
Remarks
Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or BufferedStream.Close. Setting StreamWriter.AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters.

All the read and write methods of BufferedStream automatically maintain the buffer, so there is no need to invoke Flush when switching back and forth between reading and writing.

See also:
BufferedStream.Close

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.GetLifetimeService

Summary
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
C# Syntax:
public object GetLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance.
Remarks
For more information about lifetime services, see the LifetimeServices class.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: InitializeLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.InitializeLifetimeService

Summary
Obtains a lifetime service object to control the lifetime policy for this instance.
C# Syntax:
public virtual object InitializeLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the LifetimeServices.LeaseManagerPollTime property.
Remarks
For more information about lifetime services, see the LifetimeServices class.
Example
The following code example demonstrates creating a lease.
 public class MyClass : MarshalByRefObject
 {
   public override Object InitializeLifetimeService()
   {
     ILease lease = (ILease)base.InitializeLifetimeService();
     if (lease.CurrentState == LeaseState.Initial)
     {
          lease.InitialLeaseTime = TimeSpan.FromMinutes(1);
          lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
           lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
     }
       return lease;
   }
 }

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: Read(
   in byte[] array,
   int offset,
   int count
)
Summary
Copies bytes from the current buffered stream to an array.
C# Syntax:
public override int Read(
   in byte[] array,
   int offset,
   int count
);
Parameters:

array

The buffer to which bytes are to be copied.

offset

The byte offset in the buffer at which to begin reading bytes.

count

The number of bytes to be read.

Return Value:
The total number of bytes read into array. This may be less than the number of bytes requested if that many bytes aren't currently available, or zero if the end of the stream has been reached before any data can be read.
Exceptions
Exception Type Condition
ArgumentException Length of array minus offset is less than count.
ArgumentNullException array is null.
ArgumentOutOfRangeException offset or count is negative.
IOException The stream is not open or is null.
NotSupportedException The stream does not support reading.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
The Read method will return zero only if the end of the stream is reached. In all other cases, Read always reads at least one byte from the stream before returning. By definition, if no data is available from the stream upon a call to Read, the Read method returns zero (the end of the stream is reached automatically). An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached.

Use BinaryReader for reading primitive data types.

See also:
Buffer.BlockCopy | BufferedStream.CanRead | BufferedStream.Write

Return to top


Overridden Method: ReadByte()
Summary
Reads a byte from the underlying stream and returns the byte cast to an int, or returns -1 if reading from the end of the stream.
C# Syntax:
public override int ReadByte();
Return Value:
The byte cast to an int, or -1 if reading from the end of the stream.
Exceptions
Exception Type Condition
IOException An I/O error occurs, such as the stream being closed.
NotSupportedException The stream does not support reading.
ObjectDisposedException Methods were called after the stream was closed.
Remarks


Notes to implementors: The default implementation on Stream creates a new single-byte array and then calls Stream.Read. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.

Return to top


Overridden Method: Seek(
   long offset,
   SeekOrigin origin
)
Summary
Sets the position within the current buffered stream.
C# Syntax:
public override long Seek(long offset, Seek(
   long offset,
   SeekOrigin origin
);
Parameters:

offset

A byte offset relative to origin.

origin

A value of type SeekOrigin indicating the reference point from which to obtain the new position.

Return Value:
The new position within the current buffered stream.
Exceptions
Exception Type Condition
IOException The stream is not open or is null.
NotSupportedException The stream does not support seeking.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
If offset is negative, the new position will precede the position specified by origin by the number of bytes specified by offset. If offset is zero, the new position will be the position specified by origin. If offset is positive, the new position will follow the position specified by origin by the number of bytes specified by offset.

Seeking to any location beyond the length of the stream is supported.

See also:
SeekOrigin

Return to top


Overridden Method: SetLength(
   long value
)
Summary
Sets the length of the buffered stream.
C# Syntax:
public override void SetLength(
   long value
);
Parameters:

value

An integer indicating the desired length of the current buffered stream in bytes.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException value is negative.
IOException The stream is not open or is null.
NotSupportedException The stream does not support both writing and seeking.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
The buffer is flushed before setting the length of the underlying data source or repository. If the specified value is less than the current length of the buffered stream, the buffered stream is truncated. If the specified value is larger than the current length of the buffered stream, the buffered stream is expanded. If the buffered stream is expanded, the contents of the buffered stream between the old and the new lengths are not defined.

SetLength flushes any buffered writes if necessary.

A stream must support both writing and seeking for SetLength to work.

See also:
BufferedStream.Seek

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: Write(
   byte[] array,
   int offset,
   int count
)
Summary
Copies bytes to the buffered stream and advances the current position within the buffered stream by the number of bytes written.
C# Syntax:
public override void Write(
   byte[] array,
   int offset,
   int count
);
Parameters:

array

The byte array from which to copy count bytes to the current buffered stream.

offset

The offset in the buffer at which to begin copying bytes to the current buffered stream.

count

The number of bytes to be written to the current buffered stream.

Exceptions
Exception Type Condition
ArgumentException Length of array minus offset is less than count.
ArgumentNullException array is null.
ArgumentOutOfRangeException offset or count is negative.
IOException The stream is closed or null.
NotSupportedException The stream does not support writing.
ObjectDisposedException Methods were called after the stream was closed.
Remarks


Notes to implementors: The default implementation on Stream creates a new single-byte array and then calls Stream.Write. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.
See also:
BufferedStream.CanWrite | BufferedStream.Read

Return to top


Overridden Method: WriteByte(
   byte value
)
Summary
Writes a byte to the current position in the buffered stream.
C# Syntax:
public override void WriteByte(
   byte value
);
Parameters:

value

A byte to write to the stream.

Exceptions
Exception Type Condition
NotSupportedException The stream does not support writing.
ArgumentNullException value is null.
ObjectDisposedException Methods were called after the stream was closed.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.