System.IO.Stream

Represents an abstract base class for all streams. Provides a base implementation for several stream operations, and includes event handling for stream-related events.

Overview

The Stream class is an abstract base class that provides fundamental methods and properties for working with sequences of bytes. It serves as the foundation for various specialized stream types in .NET, such as FileStream, MemoryStream, and NetworkStream. Streams enable reading from and writing to data sources, whether they are files, memory buffers, network connections, or other input/output devices.

Key Features:

Abstract Methods

Properties

Methods

Abstract Methods Details

Read

Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

public abstract int Read(byte[] buffer, int offset, int count);

Parameters:

Name Type Description
buffer byte[] The buffer to read data into.
offset int The zero-based offset in buffer at which to begin storing the data read from the current stream.
count int The maximum number of bytes to read.

Returns:

Type Description
int The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream has been reached.

Write

Writes bytes to the current stream and advances the position within the stream by the number of bytes written.

public abstract void Write(byte[] buffer, int offset, int count);

Parameters:

Name Type Description
buffer byte[] The buffer to write data from.
offset int The zero-based offset in buffer from which to begin writing bytes to the current stream.
count int The number of bytes to write.

Seek

Sets the current position of the stream to a value.

public abstract long Seek(long offset, SeekOrigin origin);

Parameters:

Name Type Description
offset long A byte offset relative to the origin parameter.
origin SeekOrigin A value indicating the term to use as a reference and the direction to use from that term.

Returns:

Type Description
long The new position within the current stream.

SetLength

Sets the length of the stream to a specific value.

public abstract void SetLength(long value);

Parameters:

Name Type Description
value long The desired length of the stream.

Properties Details

CanRead

Gets a value indicating whether the current stream supports reading.

public abstract bool CanRead { get; }

Returns:

Type Description
bool true if the stream supports reading; otherwise, false.

CanSeek

Gets a value indicating whether the current stream supports seeking and seeking is possible.

public abstract bool CanSeek { get; }

Returns:

Type Description
bool true if the stream supports seeking; otherwise, false.

CanWrite

Gets a value indicating whether the current stream supports writing.

public abstract bool CanWrite { get; }

Returns:

Type Description
bool true if the stream supports writing; otherwise, false.

Length

Gets the length in bytes of the stream.

public abstract long Length { get; }

Returns:

Type Description
long A long representing the length of the stream in bytes.

Position

Gets or sets the current position within the stream.

public abstract long Position { get; set; }

Returns:

Type Description
long The current position within the stream.

Remarks:

Setting the position to a value greater than the length of the stream is not supported by all streams.

Methods Details

Close

Cleans up resources and closes the stream.

public virtual void Close();

Remarks:

Calling Close() releases the resources used by the stream. For streams that manage unmanaged resources, such as file handles, this is crucial.

CopyTo

Copies all bytes from the current stream to a destination stream.

public virtual void CopyTo(Stream destination);
public virtual void CopyTo(Stream destination, int bufferSize);

Parameters:

Name Type Description
destination Stream The stream to which the contents of the current stream will be copied.
bufferSize int The size of the buffer to use for reading and writing.

CopyToAsync

Asynchronously copies all bytes from the current stream to a destination stream.

public virtual Task CopyToAsync(Stream destination);
public virtual Task CopyToAsync(Stream destination, int bufferSize);
public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken);

Parameters:

Name Type Description
destination Stream The stream to which the contents of the current stream will be copied.
bufferSize int The size of the buffer to use for reading and writing.
cancellationToken CancellationToken A token to observe for cancellation requests.

Returns:

Type Description
Task A task that represents the asynchronous copy operation.

Flush

Clears all buffers for the current stream and causes any buffered data to be written to the underlying device.

public virtual void Flush();

Remarks:

This method ensures that all pending writes are committed to the underlying storage.

Read

Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

public virtual int Read(byte[] buffer, int offset, int count);

Parameters:

Name Type Description
buffer byte[] The buffer to read data into.
offset int The zero-based offset in buffer at which to begin storing the data read from the current stream.
count int The maximum number of bytes to read.

Returns:

Type Description
int The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream has been reached.

Remarks:

This is the default implementation of the abstract Read method. Derived classes should override this method to provide their specific read functionality.

ReadByte

Reads one byte from the stream and advances the position within the stream by one byte, or returns -1 if the end of the stream has been reached.

public virtual int ReadByte();

Returns:

Type Description
int The byte read from the stream. Cast to a byte. Returns -1 if the end of the stream has been reached.

ReadAsync

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and returns the number of bytes read.

public virtual Task<int> ReadAsync(byte[] buffer, int offset, int count);
public virtual Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);

Parameters:

Name Type Description
buffer byte[] The buffer to read data into.
offset int The zero-based offset in buffer at which to begin storing the data read from the current stream.
count int The maximum number of bytes to read.
cancellationToken CancellationToken A token to observe for cancellation requests.

Returns:

Type Description
Task<int> A task that represents the asynchronous read operation, which should resolve with the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if that many bytes are not currently available, or 0 in the case of the end of the stream.

Seek

Sets the current position of the stream to a value.

public virtual long Seek(long offset, SeekOrigin origin);

Parameters:

Name Type Description
offset long A byte offset relative to the origin parameter.
origin SeekOrigin A value indicating the term to use as a reference and the direction to use from that term.

Returns:

Type Description
long The new position within the current stream.

Remarks:

This is the default implementation for Seek. Derived classes should override this method to provide their specific seeking functionality.

SetLength

Sets the length of the stream to a specific value.

public virtual void SetLength(long value);

Parameters:

Name Type Description
value long The desired length of the stream.

Remarks:

This is the default implementation for SetLength. Derived classes should override this method to provide their specific length setting functionality.

Write

Writes bytes to the current stream and advances the position within the stream by the number of bytes written.

public virtual void Write(byte[] buffer, int offset, int count);

Parameters:

Name Type Description
buffer byte[] The buffer to write data from.
offset int The zero-based offset in buffer from which to begin writing bytes to the current stream.
count int The number of bytes to write.

Remarks:

This is the default implementation for Write. Derived classes should override this method to provide their specific write functionality.

WriteByte

Writes one byte to the current stream and advances the position within the stream by one byte.

public virtual void WriteByte(byte value);

Parameters:

Name Type Description
value byte The byte to write to the stream.

WriteAsync

Asynchronously writes bytes to the current stream, advances the position within the stream by the number of bytes written, and returns the number of bytes written.

public virtual Task WriteAsync(byte[] buffer, int offset, int count);
public virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);

Parameters:

Name Type Description
buffer byte[] The buffer to write data from.
offset int The zero-based offset in buffer from which to begin writing bytes to the current stream.
count int The number of bytes to write.
cancellationToken CancellationToken A token to observe for cancellation requests.

Returns:

Type Description
Task A task that represents the asynchronous write operation.

Usage Example

Here's a basic example of reading from a file stream:

using System;\n using System.IO;\n \n public class Example\n {\n public static void Main()\n {\n try\n {\n // Create a FileStream to read from a file.\n using (FileStream fs = new FileStream("myFile.txt", FileMode.Open, FileAccess.Read))\n {\n byte[] buffer = new byte[1024]; // Buffer to store read data\n int bytesRead = fs.Read(buffer, 0, buffer.Length);\n \n // Process the bytes read (e.g., convert to string)\n string content = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);\n Console.WriteLine("Content read from file:");\n Console.WriteLine(content);\n }\n }\n catch (FileNotFoundException)\n {\n Console.WriteLine("The specified file was not found.");\n }\n catch (Exception ex)\n {\n Console.WriteLine($"An error occurred: {ex.Message}");\n }\n }\n }\n