System.IO.Stream
Provides a generic view of a sequence of bytes. This is an abstract base class for byte streams.
public abstract class Stream : IDisposable
Overview
Properties
Methods
Events
Examples
Overview
The Stream
class defines a generic interface for reading and writing a series of bytes. Derived classes implement specific storage mediums such as files, memory, network, and cryptographic streams.
- Supports synchronous and asynchronous operations.
- Provides methods for reading, writing, seeking, and flushing.
- Implements
IDisposable
for resource cleanup.
Properties
Property | Type | Description |
---|---|---|
CanRead | bool | Indicates whether the current stream supports reading. |
CanSeek | bool | Indicates whether the current stream supports seeking. |
CanWrite | bool | Indicates whether the current stream supports writing. |
Length | long | Gets the length of the stream in bytes. |
Position | long | Gets or sets the current position within the stream. |
Methods
Method | Signature | Description |
---|---|---|
Read | int Read(byte[] buffer, int offset, int count) | Reads a block of bytes from the stream and writes the data to a buffer. |
Write | void Write(byte[] buffer, int offset, int count) | Writes a block of bytes to the stream from a buffer. |
Seek | long Seek(long offset, SeekOrigin origin) | Sets the position within the current stream. |
Flush | void Flush() | Clears all buffers for the stream and causes any buffered data to be written. |
ReadAsync | Task | Asynchronously reads a block of bytes. |
WriteAsync | Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) | Asynchronously writes a block of bytes. |
CopyToAsync | Task CopyToAsync(Stream destination, int bufferSize = 81920, CancellationToken cancellationToken = default) | Asynchronously reads the bytes from the current stream and writes them to another stream. |
Dispose | void Dispose() | Releases the unmanaged resources used by the stream. |
Events
The Stream
class does not expose any events.
Examples
Reading from a file using FileStream
(derived from Stream
):
using System;
using System.IO;
class Program
{
static void Main()
{
const string path = "example.txt";
using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
Console.Write(System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead));
}
}
}
}
Writing to a memory stream:
using System;
using System.IO;
class Demo
{
static void Main()
{
using (MemoryStream ms = new MemoryStream())
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, Stream!");
ms.Write(data, 0, data.Length);
ms.Position = 0; // rewind
using (StreamReader reader = new StreamReader(ms))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}