System.IO.Stream Class

Assembly: Mscorlib.dll
Namespace: System.IO
Summary
Provides a generic view of a sequence of bytes.
C# Syntax:
[Serializable]
public abstract class Stream : MarshalByRefObject, IDisposable
Remarks
Streams involve three fundamental operations:
  1. You can read from streams. Reading is the transfer of data from a stream into a data structure, such as an array of bytes.
  2. You can write to streams. Writing is the transfer of data from a data structure into a stream.
  3. Streams can support seeking. Seeking is the querying and modifying of the current position within a stream. Seek capability depends on the kind of backing store a stream has. For example, network streams have no unified concept of a current position, and therefore typically do not support seeking.

Stream is the abstract base class of all streams. 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. The Stream class and its derived classes provide a generic view of these different types of input and output, isolating the programmer from the specific details of the operating system and the underlying devices.

Depending on the underlying data source or repository, streams might support only some of these capabilities. An application can query a stream for its capabilities by using the Stream.CanRead, Stream.CanWrite, and Stream.CanSeek properties.

The Stream.Read and Stream.Write methods read and write data in a variety of formats. For streams that support seeking, use the Stream.Seek and Stream.SetLength methods and the Stream.Position and Stream.Length properties to query and modify the current position and length of a stream.

Some stream implementations perform local buffering of the underlying data to improve performance. For such streams, the Stream.Flush method can be used to clear any internal buffers and ensure that all data has been written to the underlying data source or repository.

Calling Stream.Close on a Stream flushes any buffered data, essentially calling Flush for you.Close also releases operating system resources such as file handles, network connections, or memory used for any internal buffering. The BufferedStream class provides the capability of wrapping a buffered stream around another stream in order to improve read and write performance.

If you need a stream with no backing store (also known as a bit bucket), use Stream.Null.



Notes to implementors: When implementing a derived class of Stream, you must provide implementations for the Stream.Read and Stream.Write methods. The asynchronous methods Stream.BeginRead, Stream.EndRead, Stream.BeginWrite, and Stream.EndWrite are implemented through the synchronous methods Read and Write. Similarly, your implementations of Read and Write will work correctly with the asynchronous methods. The default implementations of Stream.ReadByte and Stream.WriteByte create a new single-element byte array, and then call your implementations of Read and Write. When deriving from Stream, if you have an internal byte buffer, it is strongly recommended that you override these methods to access your internal buffer for substantially better performance. You must also provide implementations of Stream.CanRead, Stream.CanSeek, Stream.CanWrite, Stream.Flush, Stream.Length, Stream.Position, Stream.Seek, and Stream.SetLength.
See also:
System.IO Namespace | FileStream | MemoryStream | BufferedStream

System.IO.Stream Member List:

Public Fields
Null
Public Properties
CanRead Read-only

When overridden in a derived class, gets a value indicating whether the current stream supports reading.
CanSeek Read-only

When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
CanWrite Read-only

When overridden in a derived class, gets a value indicating whether the current stream supports writing.
Length Read-only

When overridden in a derived class, gets the length in bytes of the stream.
Position Read-write

When overridden in a derived class, gets or sets the position within the current stream.
Public Methods
BeginRead Begins an asynchronous read operation.
BeginWrite Begins an asynchronous write operation.
Close Closes the current stream and releases any resources (such as sockets and file handles) associated with the current 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 Waits for the pending asynchronous read to complete.
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 When overridden in a derived class, 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 When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
ReadByte Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Seek When overridden in a derived class, sets the position within the current stream.
SetLength When overridden in a derived class, sets the length of the current 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 When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
WriteByte Writes a byte to the current position in the stream and advances the position within the stream by one byte.
Protected Constructors
ctor #1 Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Protected Methods
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.Stream Member Details

ctor #1
Summary:
Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
protected Stream();

Return to top


Field: Null
Summary
A Stream with no backing store.
C# Syntax:
public static readonly Stream Null;
Remarks
Use Null to redirect output to a stream that will not consume any operating system resources. When the methods of Stream that provide writing are invoked on Null, the call simply returns, and no data is written.Null also implements a Read method that returns zero without reading data.

Return to top


Property: CanRead (read-only)
Summary
When overridden in a derived class, gets a value indicating whether the current stream supports reading.
C# Syntax:
public abstract bool CanRead {get;}
Remarks
If a class derived from Stream does not support reading, calls to the Stream.Read, Stream.ReadByte, and Stream.BeginRead methods throw a NotSupportedException.

If the stream is closed, this property returns false.

Example
The following is an example of using the CanRead property.
 using System;
 using System.IO;
 
class TestRW 
{
   public static void Main(String[] args)
   {
 
      FileStream fs = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.Read);
         if (fs.CanRead && fs.CanWrite)
         {
            Console.WriteLine("MyFile.txt can be both written to and read from.");
         }
         else if (fs.CanRead)
         {
            Console.WriteLine("MyFile.txt is not writable.");
      }
   }
}
 //This code outputs "MyFile.txt is not writable."
 //To get the output message "MyFile.txt can be both written to and read from.",
 //change the FileAccess parameter to ReadWrite in the FileStream constructor.

    

Return to top


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

If the stream is closed, this property returns false.

Return to top


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

If the stream is closed, this property returns false.

Example
The following is an example of using the CanWrite property.
 using System;
 using System.IO;
 
 class TestRW 
 {
   public static void Main(String[] args)
   { 
     FileStream fs = new FileStream("MyFile.txt", FileMode.OpenOrCreate,
        FileAccess.Write);
     if (fs.CanRead && fs.CanWrite) {
         Console.WriteLine("MyFile.txt can be both written to and read from.");
     }
     else if (fs.CanWrite) {
         Console.WriteLine("MyFile.txt is writable.");
     }
   }
 }
 //This code outputs "MyFile.txt is writable."
 //To get the output message "MyFile.txt can be both written to and read from.",
 //change the FileAccess parameter to ReadWrite in the FileStream constructor.

    

Return to top


Property: Length (read-only)
Summary
When overridden in a derived class, gets the length in bytes of the stream.
C# Syntax:
public abstract long Length {get;}
Exceptions
Exception Type Condition
NotSupportedException A class derived from Stream does not support seeking.
ObjectDisposedException Methods were called after the stream was closed.
Example
The following is an example of using the Length and Position properties.
 if( s.Length==s.Position )
 {
    Console.WriteLine("End of file has been reached.");
 }

    

Return to top


Property: Position (read-write)
Summary
When overridden in a derived class, gets or sets the position within the current stream.
C# Syntax:
public abstract long Position {get; set;}
Exceptions
Exception Type Condition
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 stream must support seeking to get or set the position. Use the Stream.CanSeek property to determine whether the stream supports seeking.

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

The Position property does not keep track of the number of bytes from the stream that have been consumed, skipped, or both.

Example
The following is an example of using the Length and Position properties.
 if( s.Length==s.Position )
 {
    Console.WriteLine("End of file has been reached.");
 }

    

Return to top


Method: BeginRead(
   byte[] buffer,
   int offset,
   int count,
   AsyncCallback callback,
   object state
)
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
)
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


Method: Close()
Summary
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
C# Syntax:
public virtual void Close();
Remarks
Flushing the stream will not flush its underlying encoder unless you explicitly call an implementation of Stream.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.

A call to Close is required for proper operation of a stream. Following a call to Close, other operations on the stream could throw exceptions. If the stream is already closed, a call to Close throws no exceptions.

Attempts to manipulate the stream after the stream has been closed might throw an ObjectDisposedException.

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()
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
)
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
)
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:
~Stream();

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

Return to top


Method: Flush()
Summary
When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
C# Syntax:
public abstract void Flush();
Exceptions
Exception Type Condition
IOException An I/O error occurs, such as the file being already closed.
Remarks
Override Flush on streams that implement a buffer. Use this method to move any information from an underlying buffer to its destination, clear the buffer, or both. Depending upon the state of the object, you might have to modify the current position within the stream (for example, if the underlying stream supports seeking). For additional information see Stream.CanSeek.

Flushing the stream will not flush its underlying encoder unless you explicitly call an implementation of Flush or Stream.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.

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


Method: Read(
   in byte[] buffer,
   int offset,
   int count
)
Summary
When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
C# Syntax:
public abstract int Read(
   in byte[] buffer,
   int offset,
   int count
);
Parameters:

buffer

An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count) replaced by the bytes read from the current source.

offset

The zero-based byte offset in buffer at which to begin storing the data read from the current stream.

count

The maximum number of bytes to be read from the current stream.

Return Value:
The total number of bytes read into the buffer. This may be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
Exceptions
Exception Type Condition
ArgumentException The sum of offset and count is larger than the buffer length.
ArgumentNullException buffer is null.
ArgumentOutOfRangeException offset or count is negative.
IOException An I/O error occurs.
NotSupportedException The stream does not support reading.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
Use the Stream.CanRead property to determine whether the current instance supports reading.

The default implementation of Read calls the asynchronous Stream.BeginRead method.

Implementations of this method read a maximum of count bytes from the current stream and store them in buffer beginning at offset. The current position within the stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the stream remains unchanged. Implementations return the number of bytes read. The return value is zero only if the position is currently at the end of the stream. The implementation will block until at least one byte of data can be read, in the event that no data is available.Read returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). 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.

Example
The following is an example of using the Length and Position properties.
if( s.Length==s.Position )
 {
 Console.WriteLine("End of file has been reached.");
 }

    

The following example shows how to use Read in a blocking fashion.


 public class Block
 {
     public static void Main()
     {
         Stream s = new MemoryStream();
         for (int i=0; i<100; i++)
           s.WriteByte((byte)i);
           s.Position = 0;
 
         // Now read in s into a byte buffer.
         byte[] bytes = new byte[1000];
         int numBytesToRead = (int) s.Length;
         int numBytesRead = 0;
         while (numBytesToRead > 0) 
         {
             // Read may return anything from 0 to numBytesToRead.
             int n = s.Read(bytes, numBytesRead, numBytesToRead);
             if (n==0)  // We're at EOF
                 break;
             numBytesRead += n;
             numBytesToRead -= n;
         }
         s.Close();
         // numBytesToRead should be 0 now, and numBytesRead should
         // equal 100.
         Console.WriteLine("number of bytes read: "+numBytesRead);
     }
 }

    

Return to top


Method: ReadByte()
Summary
Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
C# Syntax:
public virtual int ReadByte();
Return Value:
The unsigned byte cast to an Int32, or -1 if at the end of the stream.
Exceptions
Exception Type Condition
IOException The stream is closed.
NotSupportedException The stream does not support reading.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
Use the Stream.CanRead property to determine whether the current instance supports reading.

Attempts to manipulate the stream after the stream has been closed could throw an ObjectDisposedException.



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


Method: Seek(
   long offset,
   SeekOrigin origin
)
Summary
When overridden in a derived class, sets the position within the current stream.
C# Syntax:
public abstract long Seek(long offset, Seek(
   long offset,
   SeekOrigin origin
);
Parameters:

offset

A byte offset relative to origin. 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.

origin

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

Return Value:
The new position within the current stream.
Exceptions
Exception Type Condition
IOException An I/O error occurs, such as the stream being closed.
NotSupportedException The stream does not support seeking, such as if the stream is constructed from a pipe or console output.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
Use the Stream.CanSeek property to determine whether the current instance supports seeking.

If offset is negative, the new position is required to precede the position specified by origin by the number of bytes specified by offset. If offset is zero (0), the new position is required to be the position specified by origin. If offset is positive, the new position is required to follow the position specified by origin by the number of bytes specified by offset.

If you intend to use a file as a backing store for a stream implementation, you must override Seek to set the Stream.Position property one byte beyond the end of the stream. Opening a new file and then writing to it requires that the position be set to one byte beyond the end of the stream. The position cannot be set to more than one byte beyond the end of the stream.

Classes derived from Stream that support seeking must override this method to provide the functionality described above.

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

Example
This example shows a use of SeekOrigin with StreamReader.BaseStream and Seek to set the file pointer of the underlying stream to the beginning.
 FileStream fs = new FileStream("log.txt", FileMode.OpenOrCreate,
    FileAccess.Read);
 // Create a Char reader.
 StreamReader w = new StreamReader(fs);
 // Set the StreamReader file pointer to the end.
 w.BaseStream.Seek(0, SeekOrigin.End);

    

Return to top


Method: SetLength(
   long value
)
Summary
When overridden in a derived class, sets the length of the current stream.
C# Syntax:
public abstract void SetLength(
   long value
);
Parameters:

value

The desired length of the current stream in bytes.

Exceptions
Exception Type Condition
IOException An I/O error occurs, such as the file being closed.
NotSupportedException The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
If the specified value is less than the current length of the stream, the stream is truncated. If the specified value is larger than the current length of the stream, the stream is expanded. If the stream is expanded, the contents of the stream between the old and the new length are not defined.

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

Use the Stream.CanWrite property to determine whether the current instance supports writing, and the Stream.CanSeek property to determine whether seeking is supported.

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


Method: Write(
   byte[] buffer,
   int offset,
   int count
)
Summary
When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
C# Syntax:
public abstract void Write(
   byte[] buffer,
   int offset,
   int count
);
Parameters:

buffer

An array of bytes. This method copies count bytes from buffer to the current stream.

offset

The zero-based byte offset in buffer at which to begin copying bytes to the current stream.

count

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

Exceptions
Exception Type Condition
ArgumentException The sum of offset and count is greater than the buffer length.
ArgumentNullException buffer is null.
ArgumentOutOfRangeException offset or count is negative.
IOException An I/O error occurs, such as the file being closed.
NotSupportedException The stream does not support writing, or the stream is already closed.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
Use the Stream.CanWrite property to determine whether the current instance supports writing.

If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged.

The default implementation calls the asynchronous Stream.BeginWrite method.

Example
The following example demonstrates how to use the Write method to copy an input stream to an output stream.
const int size = 4096;
byte[] bytes = new byte[4096];
int numBytes;
while((numBytes = input.Read(bytes, 0, size)) > 0)
    output.Write(bytes, 0, numBytes);

    

Return to top


Method: WriteByte(
   byte value
)
Summary
Writes a byte to the current position in the stream and advances the position within the stream by one byte.
C# Syntax:
public virtual void WriteByte(
   byte value
);
Parameters:

value

The byte to write to the stream.

Exceptions
Exception Type Condition
IOException The stream is closed.
NotSupportedException The stream does not support writing, or the stream is already closed.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
Use the Stream.CanWrite property to determine whether the current instance supports writing.

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.

Return to top


Top of page

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