[Serializable] |
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.
Null |
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. |
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. |
ctor #1 | Default constructor. This constructor is called by derived class constructors to initialize state in this type. |
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:
protected Stream(); |
public static readonly Stream Null;
|
public abstract bool CanRead {get;}
|
If the stream is closed, this property returns false.
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.
public abstract bool CanSeek {get;}
|
If the stream is closed, this property returns false.
public abstract bool CanWrite {get;}
|
If the stream is closed, this property returns false.
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.
public abstract long Length {get;}
|
Exception Type | Condition |
---|---|
NotSupportedException | A class derived from Stream does not support seeking. |
ObjectDisposedException | Methods were called after the stream was closed. |
if( s.Length==s.Position ) { Console.WriteLine("End of file has been reached."); }
public abstract long Position {get; set;}
|
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. |
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.
if( s.Length==s.Position ) { Console.WriteLine("End of file has been reached."); }
public virtual IAsyncResult BeginRead( |
buffer
offset
count
callback
state
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. |
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.
public virtual IAsyncResult BeginWrite( |
buffer
offset
count
callback
state
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. |
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.
public virtual void Close(); |
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.
requestedType
Exception Type | Condition |
---|---|
RemotingException | This instance is not a valid remoting object. |
protected virtual WaitHandle CreateWaitHandle(); |
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.
public virtual int EndRead( |
asyncResult
Exception Type | Condition |
---|---|
ArgumentNullException | asyncResult is null. |
ArgumentException | asyncResult did not originate from a Stream.BeginRead method on the current stream. |
EndRead can be called once on every IAsyncResult from Stream.BeginRead.
This method blocks until the I/O operation has completed.
public virtual void EndWrite( |
asyncResult
Exception Type | Condition |
---|---|
ArgumentNullException | asyncResult is null. |
ArgumentException | asyncResult did not originate from a Stream.BeginWrite method on the current stream. |
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.
~Stream(); |
public abstract void Flush(); |
Exception Type | Condition |
---|---|
IOException | An I/O error occurs, such as the file being already closed. |
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.
public virtual int GetHashCode(); |
public object GetLifetimeService(); |
public Type GetType(); |
public virtual object InitializeLifetimeService(); |
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; } }
protected object MemberwiseClone(); |
buffer
offset
count
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. |
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.
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); } }
public virtual int ReadByte(); |
Exception Type | Condition |
---|---|
IOException | The stream is closed. |
NotSupportedException | The stream does not support reading. |
ObjectDisposedException | Methods were called after the stream was closed. |
Attempts to manipulate the stream after the stream has been closed could throw an ObjectDisposedException.
public abstract long Seek(long offset, Seek( |
offset
origin
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. |
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.
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);
public abstract void SetLength( |
value
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. |
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.
public virtual string ToString(); |
buffer
offset
count
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. |
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.
const int size = 4096; byte[] bytes = new byte[4096]; int numBytes; while((numBytes = input.Read(bytes, 0, size)) > 0) output.Write(bytes, 0, numBytes);
public virtual void WriteByte( |
value
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. |