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.

Properties

PropertyTypeDescription
CanReadboolIndicates whether the current stream supports reading.
CanSeekboolIndicates whether the current stream supports seeking.
CanWriteboolIndicates whether the current stream supports writing.
LengthlongGets the length of the stream in bytes.
PositionlongGets or sets the current position within the stream.

Methods

MethodSignatureDescription
Readint Read(byte[] buffer, int offset, int count)Reads a block of bytes from the stream and writes the data to a buffer.
Writevoid Write(byte[] buffer, int offset, int count)Writes a block of bytes to the stream from a buffer.
Seeklong Seek(long offset, SeekOrigin origin)Sets the position within the current stream.
Flushvoid Flush()Clears all buffers for the stream and causes any buffered data to be written.
ReadAsyncTask ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)Asynchronously reads a block of bytes.
WriteAsyncTask WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)Asynchronously writes a block of bytes.
CopyToAsyncTask CopyToAsync(Stream destination, int bufferSize = 81920, CancellationToken cancellationToken = default)Asynchronously reads the bytes from the current stream and writes them to another stream.
Disposevoid 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());
            }
        }
    }
}